I'm working on a program for an intro to java class and am supposed to use the following interface:

public Interface Animal{ 
//The animal is first supposed to "speak" and then it gets to eat
//As long as the food supply lasts
public void feed(); 
//The animal eats
public void eat(); 
//The animal "talks" 
public void talk(); 
//Print the name of the animal and then number of days
//that the food will still last.
public void print(); 
}

The assignment says that we're supposed to write an abstract class Pet that has object variables for the names of the animals as well as the food supply (given through a constructor) - but I'm confused at how to use object variables in a constructor to set the names and food supply. Can anyone help?

I'm working on a program for an intro to java class and am supposed to use the following interface:

public Interface Animal{ 
//The animal is first supposed to "speak" and then it gets to eat
//As long as the food supply lasts
public void feed(); 
//The animal eats
public void eat(); 
//The animal "talks" 
public void talk(); 
//Print the name of the animal and then number of days
//that the food will still last.
public void print(); 
}

The assignment says that we're supposed to write an abstract class Pet that has object variables for the names of the animals as well as the food supply (given through a constructor) - but I'm confused at how to use object variables in a constructor to set the names and food supply. Can anyone help?

Maybe this may be of help, java docs on constructors and initiating variables:http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html, and also this:http://www.coderanch.com/t/253368/java-programmer-SCJP/certification/constructor-abstract-class

Edited 4 Years Ago by DavidKroukamp: n/a

Do you mean like this?

public Pet(string petName, double foodAmount) {
		name = petName;
		amount = foodAmount;
	}

Do you mean like this?

public Pet(string petName, double foodAmount) {
		name = petName;
		amount = foodAmount;
	}

That looks fine to me. Just aslong as you declared name and amount in the abstract class itself

Edited 4 Years Ago by DavidKroukamp: n/a

Oops! I meant:

public Pet(String petName, double foodAmount) {
		this.petName = petName;
		this.foodAmount = foodAmount;
	}

Thank you!

Is this the proper way to call that constructor from the subclass Dog?

public class Dog extends Pet {
	public Dog(String petName, double foodAmount) {
		super(petName, foodAmount);
	}

Thank you!

Is this the proper way to call that constructor from the subclass Dog?

public class Dog extends Pet {
	public Dog(String petName, double foodAmount) {
		super(petName, foodAmount);
	}

As far as my knowledge extends yes :)

This question has already been answered. Start a new discussion instead.