• Post Reply Bookmark Topic Watch Topic
  • New Topic

Simple Array List and Casting Questions  RSS feed

 
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys, I have a couple questions that I need to clarify up a little bit. I'm currently reading Head First Java 2nd Edition. It's pretty good so far, and I just got finished with the "Serious Polymorphism". My first question is, I need to a better understanding about specifying what an ArrayList can be limited too. For example

ArrayList<Dog> myArrayList = new ArrayList<Dog>();
Dog dogOne = new Dog();
Animal dogTwo = new Dog();

Let's also say that in my inheritance tree, I also have a Cat class and a Hippo class all extending the Animal Class.

When creating this ArrayList above, does that mean it can only store Dog objects? So if that is correct, this should work:

myArrayList.add(dogOne);

Would this work?

myArrayList.add(dogTwo);

That leads me onto my next question. Remember how all 3 classes (Dog, Cat, Hippo) all extend from the superclass Animal?

Animal aDog = new Dog();

How is that, and different from this:

Dog aDog = new Dog();

How would that benefit me at all? If you could clarify what the means and what it does that would be nice.
My Final question is I don't understand casting. Following the examples above with the same inheritance tree, can you give me some examples with casting and what it does? I would appreciate it.
 
author
Sheriff
Posts: 23513
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Ben Jass wrote:
Would this work?

myArrayList.add(dogTwo);



No. Generic type checking is done at compile time. And the the only way to confirm it 100% is to do it at runtime.

Henry
 
Henry Wong
author
Sheriff
Posts: 23513
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Ben Jass wrote:
My Final question is I don't understand casting. Following the examples above with the same inheritance tree, can you give me some examples with casting and what it does? I would appreciate it.



Casting of object types, is basically you telling the compiler to trust you. To believe that an object is of a particular type, even though it believes it is not. With generics, this is *NOT* a good idea. If you are not going to let the compiler to its job, then it would be best to just not use generics.

Henry
 
She'll be back. I'm just gonna wait here. With this tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!