Java dynamic binding when using inheritance

hashtaglulu :

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.

andresp :

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related