I am writing a “hunting-ground” application in Java. I planned the hierarchy of classes as follows:
Animal.java
public interface Animal {
void age();
void reproduce();
boolean isAlive();
void die();
}
Carnivorus.java
public abstract class Carnivorus implements Animal {
double age;
double expectancy;
boolean alive;
abstract void hunt();
}
Herbivore.java
public abstract class Herbivore implements Animal{
double age;
double expectancy;
boolean alive;
abstract void graze();
}
Lion.java
public class Lion extends Carnivorus {
Lion(double currentAge,double livesFor){
age = currentAge;
expectancy = livesFor;
alive = true;
}
@Override
public void reproduce() {
// TODO Auto-generated method stub
}
@Override
public void hunt() {
// TODO Auto-generated method stub
}
@Override
public void age() {
// TODO Auto-generated method stub
age--;
}
@Override
public void die() {
// TODO Auto-generated method stub
alive = false;
}
public boolean isAlive(){
return alive;
}
}
I noticed that the variable definitions in Carnivore and Herbivore are repeated. But since Animal is a interface, I can’t define variables there. In case I changed the Animal to a abstract class and defined the variables there, the Carnivore and Herbivore interfaces can’t extends it. What would be the proper way to design it ?
2
Yes – your problem is that the level that these animals share attributes is what should be an abstract class. You should be able to extend one abstract class with another abstract class though, like this:
Animal becomes an abstract class:
public abstract class Animal {
double age;
double expectancy;
boolean alive;
Animal(double currentAge,double livesFor) {
age = currentAge;
expectancy = livesFor;
alive = true;
}
void age() {
// TODO:
}
void reproduce() {
// TODO:
}
boolean isAlive() {
// TODO:
}
void die() {
// TODO:
}
}
Carnivorus then becomes:
public abstract class Carnivorus extends Animal {
abstract void hunt();
}
and Herbivore is now:
public abstract class Herbivore extends Animal{
abstract void graze();
}
1
But since Animal is a interface, I can’t define variables there. In
case I changed the Animal to a abstract class and defined the
variables there, the Carnivore and Herbivore interfaces can’t extends
it.
In your code Carnivore and Herbivore are not interfaces but abstract classes so they could extend Animal if you turned it into an abstract class.
In the other hand your Animal interface (if it was to remain as such) needs some methods that hint implementors of aditional state:
public interface Animal {
void age();
void reproduce();
boolean isAlive();
void die() throws AlreadyDeadException;
public double getCurrentAge();
public double getLifeExpentancy();
}
1