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 , dog .

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

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -