So I have this strucutre – an interface called Animal :
public interface Animal {
public String move ();
public String makeSound();
public String getType();
}
then an abstract class called AbstractBird which implements Anima:
public abstract class AbstractBird implements Animal {
public String birdType;
public String getType() {
return birdType;
}
@Override
public String move() {
return "Fly";
}
}
then a few classes that extends AbstractBird with the same stucture and called like Dove, Hawk, Eagle etc.. and look like this:
public class Eagle extends AbstractBird {
public Eagle() {
birdType = "Eagle";
}
@Override
public String makeSound() {
return "Noone knows";
}
}
Then is my class AnimalSound which has the main method :
public class AnimalSound {
public static void main(String[] args) {
Eagle e = new Eagle();
Dove d = new Dove();
Hawk h = new Hawk();
play(e);
play(d);
play(h);
}
public static void play(Animal a) {
System.out.println("````````````");
System.out.println(a.getType());
System.out.println(a.makeSound());
System.out.println(a.move());
}
}
As you can see I have this method getType() which returns the birdtype. The method itself is implemented in the abstract class which is OK, but still to get the correct birType I need to write constructor for each class where I can init birdType and this is the part the I don’t like much. So my question is how can I implement the getType() method in the abstract class so it returns the name of the class and/or the name of the object. I’m not sure which would be better in my example the classes have the name of the birds, but thinking of it I think that maybe there’s more sense to return to name of the object.
@Leron
here is an example:
As a result you will get proper type names and you do not need to implement constructors in each derived type. Late binding will solve this problem for you.