Question

I am playing around composition and abstract methods and classes....If I have a Animal, Cat and Dog classes here how would I make another class with Animal list using composition ???

public class SomeClass{

Animal animalList; // ?????

}

.

public abstract class Animal {


public abstract void sound();
}

.

public class Cat extends Animal {


        @Override
    public void sound() {

        System.out.println("cat makes sound");
    }
    }

.

public class Dog extends Animal {


    @Override
public void sound() {

    System.out.println("dog makes sound");
}
}
Était-ce utile?

La solution

If you are trying use Composite pattern, looks like this.

http://en.wikipedia.org/wiki/Composite_pattern

interface Animal{
    void sound();
}

class CompositeAnimal implements Animal {
    List<Animal> animals;

    @Override
    public void sound() {
        for (Animal animal : animals) {
            animal.sound();
        }
    }
}

class Dog implements Animal {
    ...
}

class Cat implements Animal {
    ...
}

Autres conseils

I think what you want is something like this

public class AnimalList{
   private List<Animal> list;

   public addAnimal(Animal a)
   {
        if !(list instanceof List)
        {
             list = new List<Animal>();
        }
        list.add(a);
   }
   //.. other stuff .. //

}

However I don't think of this as a true composition relationship. Yes the List HAS A animal. But i see the relationship more as AnimalList IS A List.

I think a better example of composition would be a class such as Person class that HAS A pet animal.

public class Person{
     private Animal pet;
     public void poke_pet()
     {
          pet.sound();
     }
}

Reference

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top