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?

Recommended Answers

All 7 Replies

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

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

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 :)

Cool! Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.