Your code makes absolutely no sense to me. I think I understand what it is you want though. First let's go through your code.
You have a Goose
class which implement Animal
which is good. Then you have a list called link
in the class:
public class Goose implements Animal{
List<Animal> link = new ArrayList<Animal>(); //remember ().
...
Each instance of your Goose
class will have a list of animals. This looks odd. From the question though, it sounds like you want 1 list which contain animals and not a list within each Goose
.
Then you have two constructors:
Goose(Duck d){
link.add(d);
}
Goose(Goose g){
link.add(g);
}
You require either a Duck
or a Goose
as input which you add to the internal list of the new Goose
. Meaning each new instance will start out with either a Duck
or a Goose
inside its list. It seems like you want your constructors to be add
methods.
Finally you have these:
Goose g3 = new Goose(new Duck()); //You were missing () here also
Goose g2 = new Goose(g2); //Syntax error. Should probably be ".. new Goose(g3);"
I am not entirely sure why you have these inside your Goose
class and they look like they are supposed to be declared elsewhere. As it is now each Goose
contain two other geese called g3
and g2
which does not make much sense either (except if they were used as reference to the parents of the goose maybe, but it does not seem to be the case).
What I think you want and how you achieve it: You need to modify your Goose
class so each goose only have members relevant for each goose. It could look like this (assuming the animal interface declare an eat()
method):
public class Goose implements Animal {
@Override
public void eat() {
// Om nom nom
}
}
You could then move link
, g2
and g3
to the 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 this you can only use the link
list in the main
method. You could also make it a property of the class containing main
to broaden the scope. If you need global access you could make a singleton class which contain it (or make it public static
somewhere, but I would recommend another approach).
You can also add a Duck
to the list if the Duck
class implements the Animal
interface correctly:
link.add(new Duck());
If the Animal
interface declares a public method called eat
you can now iterate through the list and make all the animals eat:
for(Animal a : link) {
a.eat();
}
Feel free to comment if I missed something.