Why does he always call the parent class method "doTest (double d)"?

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 doTest (double d) from the parent class and doTest (int d) from the subclass, but when I call base.doTest (3) it always calls the method of the parent class, even my object reference is different. what is the reason for this?

+4
source share
3 answers

doTest(double d)- This is a completely different method from void doTest(int d), because they have different parameter lists. There is generally no polymorphism; DerivedBaseannounces a new method without overloading Base.doTest. As if you did it:

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");
    }
}

.

base.doTest(3), doTest(double), Base, . , Base.doTest.

0

DerivedBase doTest . 2 -   doTest (double d)   doTest (int d)

, , . doTest add .

, doTest (int d), , . , .

0

, . double int . - Java,

. - .

@Override . -

class DerivedBase extends Base {
    @Override
    public void doTest(double d) {
        System.out.println("From Derived Base");
    }
}
0

Source: https://habr.com/ru/post/1670143/


All Articles