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();

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.

mashenka011041, variable has type A, but the object for which variable references has type B. That`s important difference

2023 Apr 5, 8:24:42 AM

Variable does not have type A.

2023 Feb 19, 6:04:59 PM

This is confusing me.

2022 Oct 15, 5:46:10 PM


2017 Jan 3, 9:38:56 PM

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Sign Up Now
or Subscribe for future quizzes