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.

This is confusing me.

2022 Oct 15, 5:46:10 PM


2017 Jan 3, 9:38:56 PM

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Java
Зарегистрируйся сейчас
или Подпишись на будущие тесты