I have 2 classes: Triangle and RightAngledTr. RightAngledTr inherits from Triangle. The code is as follows:
The Triangle class:
class Triangle {
public void draw() {
System.out.println(“Base::draw\n“);
}
public void computeCentroid(Triangle t) {
System.out.println Base::centroid\n“);
}
}
The RightAngledTr class:
class RightAngledTr extends Triangle {
public void draw() {
System.out.println(“RightAngle::draw\n“);
}
public void computeCentroid(RightAngled t) {
System.out.println(RtAngle::centroid\n“);
}
}
In my Driver program I have the following lines of code:
Triangle tr= new RightAngledTr ();
RightAngledTr rtr= new RightAngledTr ();
tr.computeCentroid(rtr);
tr.draw();
rtr.computeCentroid(tr);
The output I expected was:
Base::centroid
Base::draw
Base::centroid
However, the output I got was:
Base::centroid
RightAngle::draw
Base::centroid
My question is, why does tr.computeCentroid(rtr) call the Triangle class' method when tr.draw() calls the RightAngleTr class' method?
It doesn't make sense. Liskov substitution principle doesn't seem to apply.