Akshay Damle Akshay Damle - 2 months ago 13
Java Question

Inheritance and polymorphism in Java

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.

Answer

That's how java works. The draw () method is overridden.

Have a look at oracle documentation article for understanding the concepts.

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

Triangle (parent) holds the reference of RightAngledTr (child) and draw() method is invoked on child objects. It's called overriding feature.

Childs are type of parents. Parent holding child instance invokes child's overridden method. If method is not present in child, parent method will be invoked.

Overriding is redefining base class (parent) behaviour with same signature. If you change the signature of base class method in child class, it's called overloading. You have done the same for other method : computeCentroid().

But do not expect the same for same variables declared in both parent and child.

Variables are not overridden. Only methods are overridden.

Have a look at example in documentation link for better understanding

polymorphism

Comments