Karan Bijani
Karan Bijani

Reputation: 85

Java - which function is called when inheritance, polymorphism, overloading and overriding are all involved?

I have this question involving inheritance, polymorphism, overloading and overriding. I understand all these terms but not sure how they work here. Here's the code:

class A {
    public String show(D obj) {return "A and D";}
    public String show(A obj) {return "A and A";}
}
class B extends A {
    public String show(B obj) {return "B and B";}
    public String show(A obj) {return "B and A";}
}
class C extends B{}
class D extends B{}
public class whatever {
    public static void main(String[] args) {
        A a = new B(); // note the B here
        B b = new B();
        C c = new C();
        D d = new D();
        System.out.println(a.show(a)); // B and A
        System.out.println(a.show(b)); // B and A
        System.out.println(a.show(c)); // B and A
        System.out.println(a.show(d)); // A and D
    }
}

So the task here is to find the output. I have the answers already, those are the comments I put.

I understand the first one, because Java automatically does dynamic binding so a.show() calls the show() from the B class and a is of type A so B.show(A obj) is called.

The last one makes sense too, the show() method is overloaded and since d is of type D, A.show(D obj) is called which is inherited from the A class.

The other two I'm having trouble with. Well I understand that it makes sense because b and c are both A type objects technically, but why does it go with "B and A" over "B and B"?

Upvotes: 1

Views: 89

Answers (2)

ARIJIT SENGUPTA
ARIJIT SENGUPTA

Reputation: 21

Here there is two concepts one is of overloading and other is for overriding . When you create A a = new B(); it mean a is object of B and having a type of A . So when a.show(a) is executed it first encounters show(A obj) and show(B obj) method of class A and then matches the parameter with A type but 'a' is instance of B so the method show(A obj) of class B is executed.

Now when a.show(c) is executed it first encounters show(A obj) and show(B obj) methods of class A and then doesn't finds any match with the parameter of C type inside class A but still it is executed because class C extends B and B extends A.

To summarize it in short ,we can say that a.show(a) is equivalent to a.show(b) and is equivalent to a.show(c).

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691625

The declared type of a is A.

A has only two methods: one takes an A (and both b and c are instances of A), and the other takes a D (and neither b nor c are instances of D).

So the first method matches, and the second doesn't. So the first method is selected by the compiler.

This method is overridden in B, and the concrete type of a is B, so "B and A" is printed.

The method B.show(B) does not override the method A.show(A), since it doesn't take the same type as argument.

Upvotes: 3

Related Questions