Hi ranchers,
Sean Mack was asking:
So far so good but my question is, does this also apply to classes that you have defined yourself, i.e. If you put a Dog object into an ArrayList of type Animal does the Animal reference variable recognise the methods specific to the Dog object?
If you have an ArrayList of type <Animal>, you can store a Dog into it, because a dog IS-An Animal.
But what you get out of the list will always be an Animal, and you cannot invoke Dog-specific behaviour unless you
1. have the reference variable of type Dog and
2. cast to a dog.
It is just the same as if you said:
Animal dogAnimal = new Dog();
You cannot invoke Dog-methods on this dogAnimal, because the compiler knows only about the methods, that are in class Animal for this dogAnimal.
However, if Animal methods are overriden in the Dog subclass, the method invoked will be that of the object-type, of Dog in this example:
prints out:
woof!
woof!
miaw!
and:
Also does polymorphism still work if you add brand new methods for your subclass (i.e. not Overridden or Overloaded)?
Yes, see above.
Generic classes are in a way lacking some of the polymorphism, that non-generic classes have.
For example:
won't compile
while
works.
But also in the latter example: What you get out of this array will always be of an Animal reference type and of object type Dog.
Putting an Animal into this array
mixedArray [0] = new Animal();
would cause an ArrayStoreException, but no compile error.
And yes: this IS complicated...
[ October 14, 2006: Message edited by: Burkhard Hassel ]