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.
Inheritance supports the concept of reusability and reduces code length in object-oriented programming. Polymorphism allows the object to decide which form of the function to implement at compile-time (overloading) as well as run-time (overriding).
Inheritance is a powerful feature in Java. Java Inheritance lets one class acquire the properties and attributes of another class. Polymorphism in Java allows us to use these inherited properties to perform different tasks. Thus, allowing us to achieve the same action in many different ways.
Inheritance is a property pertaining to just classes whereas, polymorphism extends itself into any method and/or function. Inheritance allows the derived class to use all the functions and variables declared in the base class without explicitly defining them again.
The signatures of the computeCentroid() method are different. You are therefore not overriding, but overloading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With