Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 663
Akshay Damle Avatar asked Oct 25 '15 09:10

Akshay Damle


People also ask

What is the difference between inheritance and polymorphism in Java OOP?

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

How is inheritance useful to polymorphism in Java?

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.

Is inheritance a type of polymorphism?

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.


1 Answers

The signatures of the computeCentroid() method are different. You are therefore not overriding, but overloading.

like image 64
ndc85430 Avatar answered Sep 19 '22 21:09

ndc85430