David Goulet
David Goulet

Reputation: 53

Java Abstract class to instationize other class

Java

Simple Example for understanding: Two abstract classes, Animal and Product.

Animal has method Produce, to create new objects such as milk and eggs.

Two classes(Chicken and Cow) extending Abstract class Animal.

Two classes (Eggs and Milk) extending Abstract class Product.

There will be multiple instances of chicken cow egg and milk.

My question: Depending on the animal (chicken or cow) how can my Animal abstract class' s method (Produce) know which Product(Eggs or Milk) to instanciate.

What I tried: I tried having a static instance of egg in my chicken class, and then passing it to the animal constructor as a parameter, but that was a problem since I do not want to create an instance of egg when an instance of chicken is made. I want the animal abstract class to know if it will be making instances of eggs depending on of it was extended by chicken or cow.

Upvotes: 1

Views: 244

Answers (1)

dkatzel
dkatzel

Reputation: 31648

Well one way is to make the produce() method abstract too so the Chicken and Cow classes have to implement them.

Another perhaps worse design would be to pass in a ProductFactory object that will either be a EggFactory or a MilkFactory that can make Eggs or Milk respectively.

But I would go with the abstract produce() technique.

abstract class Animal{
    public abstract Product produce();
}

class Chicken extends Animal{

    public Product produce(){
         return new Egg();
    }
}

Upvotes: 1

Related Questions