This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I think I have a grasp on polymorphism.... here's my guess....
I think you need to do it this way....
I just thought that to override something you need to name it the same method name (and have the same parameters) as the superclass. Then if you want to do the superclasses' method too, you need to call the super.methodName(). The subclass has an arraylist because to be an animal means you (excuse the poor grammar) "HAS-A" ArrayList.
When you do things right, people won't be sure you've done anything at all.
your right, but that isn't exactly what I was asking, but I wasn't being very clear. So let's say I have a superclass with an arraylist of animals, and a feed() method that cycles through the arraylist and feeds all the animals in it. Then I make a subclass where I have an arraylist of something that extends animals, and is named the same name as the superclasses arraylist. If you call the feed method on my subclass would it uses the subclasses arraylist, or the superclasses arraylist? And if it uses the superclasses, is there any way to make it use the subclasses? I know the obvious solution is to override the feed method, but that seems counterproductive, as it would have the exact same code as the superclasses feed method.
Your right of course, thank you for the speedy answers. What I was originally trying to do I'm pretty sure is impossible, but what you did has the same effect (although it does involve more typing, sadly)
I think Embla is correct. What she didn't say (but I think it was implicit in "supertype offers an implementation") was that your MonkeyZoo does not behave as something which "IS-A" zoo. You have a List<? extends Animal> in one, then you have a List<Monkey> in the other. So you now have two Lists in the subclass. The two private fields do not override each other.
Is it possible to create a class which is Zoo<T extends Animal> whose field is a List<T>?
Okay, I see what you mean, I was trying to override variables,which isn't allowed.
Joined: Oct 13, 2005
colton peterson wrote:Okay, I see what you mean, I was trying to override variables,which isn't allowed.
Not so much "not allowed" as "not possible". The private field is regarded as only existing in one class; if you try to create another field with the same name, you end up with two independent and separate fields.