java - List of different objects that implement an interface -


i saw similar using inheritance want use interface want create single arraylist consisting of different objects. arraylist containing following objects |duck, duck, goose, duck, goose, pig| can add random ducks , geese. want example lets want eat duck , once im done duck can eat duck , iterate through each item , run "eat" method example
|could following:

public interface animal {..}  public class duck implements animal(){}  public class goose implements animal{      list<animal> link = new arraylist<animal>;  goose(duck d){      link.add(d);  } goose(goose g){      link.add(g);  }  goose g3 = new goose(new duck);  goose g2 = new goose(g2); } 

`

your code makes absolutely no sense me. think understand want though. first let's go through code.

you have goose class implement animal good. have list called link in class:

public class goose implements animal{     list<animal> link = new arraylist<animal>(); //remember ().     ... 

each instance of goose class have list of animals. looks odd. question though, sounds want 1 list contain animals , not list within each goose.

then have 2 constructors:

goose(duck d){     link.add(d); } goose(goose g){     link.add(g); } 

you require either duck or goose input add internal list of new goose. meaning each new instance start out either duck or goose inside list. seems want constructors add methods.

finally have these:

goose g3 = new goose(new duck()); //you missing () here goose g2 = new goose(g2);         //syntax error. should ".. new goose(g3);" 

i not entirely sure why have these inside goose class , supposed declared elsewhere. each goose contain 2 other geese called g3 , g2 not make sense either (except if used reference parents of goose maybe, not seem case).

what think want , how achieve it: need modify goose class each goose have members relevant each goose. (assuming animal interface declare eat() method):

public class goose implements animal {     @override     public void eat() {         // om nom nom     } } 

you move link, g2 , g3 main method:

public static void main(string[] args) {     list<animal> link = new arraylist<animal>();     goose g2 = new goose();     goose g3 = new goose();      link.add(g2);     link.add(g3);     .. 

doing can use link list in main method. make property of class containing main broaden scope. if need global access make singleton class contain (or make public static somewhere, recommend approach).

you can add duck list if duck class implements animal interface correctly:

link.add(new duck()); 

if animal interface declares public method called eat can iterate through list , make animals eat:

    for(animal : link) {          a.eat();     } 

feel free comment if missed something.


Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -