To conceptually understand inheritance, interfaces & polymorphism, I created a couple of classes to test things. The result I am getting is not the one I expected. The code is as follows:
public class Animal implements Comparable{
//Animal constructor & methods
public int compareTo(Object arg0){System.out.println("Animal.compareTo");}
}
public class Bear extends Animal{
//Bear constructor & methods
}
public class PolarBear extends Bear implements Comparable{
//PolarBear constructor & methods
public int compareTo(Object arg0) {System.out.println("PolarBear.compareTo");
I don’t get any error saying that I can’t implement Comparable again. But in my testing, I can’t get back to Animal’s compareTo method once I create a PolarBear, even though PolarBear should inherit the Animal’s compareTo. I tested the following:
Animal bobo = new PolarBear();
bobo.compareTo(null);
((PolarBear) bobo).compareTo(null);
((Animal)bobo).compareTo(null);
((Comparable) bobo).compareTo(null);
And each of them printed:
PolarBear.compareTo
Is there any way to access the Animal‘s compareTo? Logically, wouldn’t I want the ability to be able to compare the animal qualities of a PolarBear, as well as the PolarBear qualities?
It doesn’t matter that you are casting your
boboobject toPolarBear,Animal, orComparable, the run-time type of the object will always bePolarBearsince you instantiated it asTherefore whenever you call
.compareTo(wtv)it’ll call thePolarBearimplementation.This is what Polymorphism is. Read up on late binding as that’s how polymorphishm is implemented in java.
If you want to call the
compareTo(wtv)method of your parent classes, then you have to dosuper.compareTo(wtv)inside any other subclass’ methods.