Writing an abstract class for homework - here's what I have so far:

public abstract class Pet {
	String petName;
	double foodAmount;
	double foodSupply;
	int days;
	public Pet(String petName, double foodSupply) { //constructor to be used by sub-classes
		this.petName = petName;
		this.foodSupply = foodSupply;
	}
	public Pet() {//default constructor
	}
		
	public void feed() {
		while (foodSupply>foodAmount) {
			foodSupply = foodSupply-foodAmount;
		}
	public abstract void eat();
	public abstract void talk();
	public void print() {
		days = (foodSupply)%(foodAmount);
		System.out.println(petName+" : "+days+" days left of food supply.");
	}
	public static void main(String[] args) {
		Pet newPet = new Pet;
		newPet.talk();
		newPet.feed();
		newPet.print();
	}
}

I'm getting an 'illegal start of type' error for the methods eat(), talk(), and print(). Can anyone help?

Recommended Answers

All 4 Replies

I got rid of that error! Sorry- found the missing culprit }. Now the only error is when I try to create 'newPet'.

public abstract class Pet {
	String petName;
	double foodAmount;
	double foodSupply;
	int days;
	public Pet(String petName, double foodSupply) { //constructor to be used by sub-classes
		this.petName = petName;
		this.foodSupply = foodSupply;
	}
	public Pet() {//default constructor
	}
		
	public void feed() {
		while (foodSupply>foodAmount) {
			foodSupply = foodSupply-foodAmount;
		}
	}
	public abstract void eat();
	public abstract void talk();
	public void print() {
		days = (foodSupply)%(foodAmount);
		System.out.println(petName+" : "+days+" days left of food supply.");
	}
	public static void main(String[] args) {
		Pet newPet = new Pet;
		newPet.talk();
		newPet.feed();
		newPet.print();
	}
}

you can't instantiate an abstract class.
that 's not an error, it's a feature of java.
you'll have to create a new class that extends the Pet class and that implements all the abstract methods, and create instances of that one.

commented: brilliantly put +7

That is NOT an error of Java, you cannot instantiate an abstract class, because it is abstract! You shoul override it with another class, override the abstract methods in that class, and now you can create objects from that class!

That is NOT an error of Java, you cannot instantiate an abstract class, because it is abstract! You shoul override it with another class, override the abstract methods in that class, and now you can create objects from that class!

and this is different from my post because ... ?

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.