Results 1 to 13 of 13
Thread: Casting Object to another type
- 04-02-2010, 03:53 PM #1
Member
- Join Date
- Apr 2010
- Posts
- 5
- Rep Power
- 0
Casting Object to another type
I have a problem with type casting!
Java Code:public class MyCollection<E>{ protected E[] elements; protected int top; public static final int SIZE = 10; public MyCollection() { [B]elements = (E[]) new Object[SIZE];[/B] top = -1; } } ... public class Test { public void draw(MyCollection<? extends Shape> list){ for( int i = 0 ; i<=list.top ; i++) [B] list.elements[i].[/B]draw(); // compile error - can't cast Object to Shape } public static void main(String[] args) { MyCollection<Shape> list = new MyCollection<Shape>(); Test test = new Test(); list.push(new Circle()); // extends Shape , push a new Circle to list list.push(new Square()); // extends Shape list.push(new Triangle()); // extends Shape test.draw(list); } }
Last edited by green_river48; 04-02-2010 at 06:14 PM.
- 04-02-2010, 05:56 PM #2
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,370
- Blog Entries
- 1
- Rep Power
- 23
Before that,
Java Code:list.elements[i].draw();
- 04-02-2010, 06:01 PM #3
Member
- Join Date
- Apr 2010
- Posts
- 5
- Rep Power
- 0
- 04-02-2010, 06:05 PM #4
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,370
- Blog Entries
- 1
- Rep Power
- 23
I'm confusing. As far as I know there is no such draw() method in the Shape interface.
- 04-02-2010, 06:13 PM #5
Member
- Join Date
- Apr 2010
- Posts
- 5
- Rep Power
- 0
- 04-02-2010, 06:20 PM #6
Senior Member
- Join Date
- Mar 2010
- Posts
- 952
- Rep Power
- 9
- 04-02-2010, 06:30 PM #7
Member
- Join Date
- Apr 2010
- Posts
- 5
- Rep Power
- 0
- 04-03-2010, 03:25 AM #8
i am newbie an have a confusion seeing your code
Can we have more than one public class in a java program?
- 04-03-2010, 05:05 AM #9
You can have at most one top-level public class in a compilation unit.
Packages
db
- 04-03-2010, 07:05 AM #10
- 04-03-2010, 09:33 AM #11
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 14,421
- Blog Entries
- 7
- Rep Power
- 26
- 04-03-2010, 09:48 AM #12
- 04-03-2010, 10:52 AM #13
Member
- Join Date
- Apr 2010
- Posts
- 5
- Rep Power
- 0
Similar Threads
-
Object casting
By spiderweb in forum Advanced JavaReplies: 5Last Post: 08-20-2009, 05:43 PM -
help with type casting.
By ramsrocker in forum Java AppletsReplies: 15Last Post: 02-26-2009, 11:28 PM -
type casting
By alvations in forum New To JavaReplies: 1Last Post: 10-13-2008, 07:07 PM -
type casting array?
By willemjav in forum Advanced JavaReplies: 5Last Post: 08-27-2008, 10:25 PM -
Type Casting Help
By rhm54 in forum New To JavaReplies: 2Last Post: 02-07-2008, 12:06 PM
Bookmarks