Inheritance and polymorphism in Java

I have 2 classes: Triangleand RightAngledTr. RightAngledTrinherited from Triangle. The code is as follows:

Grade Triangle:

class Triangle {
    public void draw() { 
        System.out.println("Base::draw\n");
    }

    public void computeCentroid(Triangle t) {
        System.out.println Base::centroid\n");
    }
}

Grade RightAngledTr:

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);

Expected Result:

Base::centroid
Base::draw
Base::centroid

However, the output I received was:

Base::centroid
RightAngle::draw
Base::centroid

My question is: why does tr.computeCentroid(rtr)the Triangleclass tr.draw()method call when does the class method call RightAngleTr?

It does not make sense. The Liskov replacement principle does not seem to apply.

+4
source share
3 answers

How java works The draw () method is overridden.

Look at the oracle article for understanding concepts.

(, ) .

Triangle (parent) RightAngledTr (child) draw() . .

- . . , .

Overriding () . , . : computeCentroid().

, .

. .

+1

computeCentroid() . , .

+3

You call the draw method on a specialized object. Even when you wrap it in a base class, you call the method overridden by a draw.

+1
source

Source: https://habr.com/ru/post/1613083/


All Articles