java - Getting to the subclass from superclass objects list -
I have a class, say - animal . And some sections that inherit from it, we say:
birds ,
cat ,
Now let me add an array of animal types, and some examples of its sub-classes.
Private list & gt; Animals & gt; List = New Arrestist & lt; Animals & gt; (); List.add (new bird ()); list.add (new bird ()); List.add (new cat ()); List.add (new dog ()); Then I repeat through this list, call some methods, etc.
for (int i = 0; i OK. But what if I would like to add a bird method, which will not be applied in the animal superclass? Suppose, fly () method, then it looks like this:
for (int i = 0; i & lt; list.length; i + +) {List .Get (i) .makeSound (); If (list.get (i) breed example) {list.get (i) .fly (); // error here}} This makes sense, but it throws an error - the symbol can not be found animal in the class to implement this method It seems to solve this issue, but I have to do this many times when there is pain in my eyes, is there any way to solve this issue?
You cast >:
(Bird) list.get (i)). Fly ();
Comments
Post a Comment