user3077292
user3077292

Reputation: 21

Constructor has object of abstract class as parameter

I have an interface called IGrocery with one method public String getName(). Then there is one abstract class called AbstractFood which implements the interface and which has a variable protected String name. Further there is one public class Ingredient (with one private double amount) which must have a constructor like this:

public Ingredient(AbstractFood food, double amount){
    this.amount=amount;
    ???
}

I don't understand how I can create an Ingredient object, as I would have to create an AbstractFood object before that (but the AbstractFood class is abstract).

Upvotes: 2

Views: 178

Answers (2)

Sage
Sage

Reputation: 15418

  • Create a subclass extending the abstract class
  • If you don't want first approach: then use anonymous class approach:

    AbstractFood aFood = new AbstractFood() 
                                 {
                                     // your implementation
                                 };
    new Ingredient(aFood, someDoubleVal);
    

Upvotes: 0

Dylan Meeus
Dylan Meeus

Reputation: 5802

You have a class that inhertices from AbstractFood say:

public class Peanut extends AbstractFood
{
   public Peanut(){
     //code
   }
}

That way, you could give an instance of "Peanut" as parameter to the constructor :)

Upvotes: 3

Related Questions