Jayakeerthi
Jayakeerthi

Reputation: 19

This inheritance program when executed gives output '2'. How?

class A { }

class B extends A { }

class C extends B { }

public class MainClass  {

    static void overloadedMethod(A a) {
        System.out.println("1");
    }

    static void overloadedMethod(B b) {
        System.out.println("2");
    }

    static void overloadedMethod(Object obj) {
        System.out.println("3");
    }

    public static void main(String[] args) {
        C c = new C();
        overloadedMethod(c);
    }
}

This inheritance program when executed gives output 2. How?

Upvotes: 0

Views: 90

Answers (2)

Blasanka
Blasanka

Reputation: 22437

Well, you know that here C class is a child class of B and B is a child class of A. Class A is also a child class of Object class(you cannot see it because it is determined at compile time).

Documentation:

Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.

Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.

So, what is the closest and most suitable class for class C.

C c = new C();
overloadedMethod(c);

It's parent class B right!. When you overload the method compiler will choose the:

static void overloadedMethod(B b) {
    System.out.println("2");
}

Since, Object class in the top of class heirarchy and class A is the grand parent of C.

Upvotes: 0

Eran
Eran

Reputation: 393811

Well, an instance of class C can be passed to any of these three overloadedMethod methods, so the compiler selects the method whose arguments have the most specific type - static void overloadedMethod(B b) - since B is a sub-class of A, which is a sub-class of Object, and therefore B is more specific than both A and Object.

Upvotes: 1

Related Questions