0

For the following code:

class A { 
    public void ex(Object o) {
        System.out.println("A");
    }
}

class B extends A { 
    public void ex(B o) {
        System.out.println("B");
    }
}

class C extends B {
    public void ex(A o) {
        System.out.println("C");
    }
}

public class Main {
    public static void main(String argv[]) {
        C xx;
        xx = new C();
        xx.ex(xx); // This prints B
    }
}

Why is the result of calling the ex method "B"? Both the reference and class type are C, still the method executed is the one from the superclass.

1 Answer 1

2

Due to the class chain you created C instances will have all 3 methods available:

  • A.ex(Object)
  • B.ex(B)
  • C.ex(A)

All of them could be used for your xx.ex(xx) invocation. At this point, according to the Java spec, the most specific method is invoked.

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

As you don't have an ex(C) method, the most specific method that matches your invocation is B.ex(B) as B is a subclass of A, which is a subclass of Object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.