What is the result of the following code compilation?

class A {
    public void m(Number n) {
        n = 5 / 3;
        System.out.println("class A, method m : " + n);
    }
}

class B extends A {
    public void m(Double d) {
        d = d / 3;
        System.out.println("class B, method m : " + d);
    }
}

public class MainClass {
    public static void main(String args[]) {
        A a = new B();
        a.m(5.0);
    }
}
Explanation

Explanation: polymorphic method invocation doesn't occur because void m (Number n) and void m (Double d) signatures differ. The fact that Double is inherited from Number doesn't matter.

Variable has type A. Therefore, an a.m() method can only call a method, which is present in the A class (or, of course, his overriden version from class B). Class A contains only one method named m. Therefore, if it is called, then it may only be a method with the m(Number) signature. Class B also contains a method named m, but it has a different (!) set of parameters. Consequently, it does not override the original method. Therefore, only A.m(Number) can be called in this example. It only remains to verify that the given parameter can be passed to this method (would not it cause a compilation error?) and calculate the value of 5/3.

hmm

2017 Jan 3, 9:38:56 PM

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback