Divvij Chandna
Divvij Chandna

Reputation: 27

Why is dynamic binding not taking place in line 3?

class A {
    public void fun(double d) {
        System.out.println("A");
    }
}

class B {
    public void fun(int i) {
        System.out.println("B");
    }
}

class C extends A {
    public void fun(int i) {
        System.out.println("C");
    }
}

class D extends B {
    public void fun(double d) {
        System.out.println("D");
    }
}

class E extends B {
    public void fun(double d) {
        System.out.println("E");
    }
    public void fun(int i) {
        System.out.println("F");
    }
}

public class Test {

    public static void main(String[] args) {
        C c = new C(); c.fun(6); //line 1
        D d = new D(); d.fun(6); //line 2
        A x = new C(); x.fun(6); //line 3
        B y = new D(); y.fun(6); //line 4
        B z = new E(); z.fun(6); //line 5
    }

}

The output to this code is: C B A B F

Not sure why output for line 3 is not "C" but it is "A". Shouldn't the method in class be called since dynamic binding is taking place?

For the code in line 5, dynamic binding takes place and the output is "F" instead of "B" but the same doesn't happen for line 3.

Upvotes: 0

Views: 91

Answers (1)

Eran
Eran

Reputation: 394146

Dynamic binding applies for methods having the same signature.

When you call a method for variable x, whose compile time type is A, only methods defined in class A (or its super-classes) can be considered by the compiler (method overloading resolution takes place during compile time). This means only public void fun(double d) is considered.

Since C's public void fun(int i) has a different signature, it doesn't override A's method, and therefore it can't be executed, even though the runtime type of the variable x is C.

In line 5 the behavior is different. Here the compile time type of z is B, and class B has a public void fun(int i) method. Since the runtime type of z is E, and E also has a method with the signature public void fun(int i), E's method overrides B's method, and therefore E's method is executed.

Upvotes: 7

Related Questions