Java – why does it always call the parent method “dotest (double D)”?

See English answers > polymer in overloaded and overridden methods 4

class PolymorphisomTest {

    class Base {
        public void doTest(double d) {
            System.out.println("From Base");
        }
    }

    class DerivedBase extends Base {

        public void doTest(int d) {
            System.out.println("From Derived Base");
        }
    }

    public void use(Base  base) {
        base.doTest(3);
    }
    public void run() {
        use(new Base());
        use(new DerivedBase ());
    }
    public static void main(String []cmd) {
        new PolymorphisomTest ().run();
    }
}

Here is the dotest (double D) from the parent class and the dotest (int d) from the child class, but when I call base When dotest (3), it always calls the parent method, even if my object reference is different What is the reason behind this?

Solution

Dotest (double D) is a completely different method from void dotest (int d) because they have different parameter lists In fact, there is no polymorphism at all; Derivedbase declares a new method instead of overloading base doTest. It's like you did this:

class Base {
    public void doTest(double d) {
        System.out.println("From Base");
    }
}

class DerivedBase extends Base {
    public void doSomethingElse(int d) {
        System.out.println("From Derived Base");
    }
}

Changing the type of a parameter changes the method signature and makes it a new method, not a method that overrides the parent class

When you call base When dotest (3), the compiler will call dotest (double), because this is the only method that the base class matches the parameters Because the method is not overwritten by anything, base. Is called doTest.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>