Java多态顶级方法被调用

Aus*_*tin -2 java polymorphism inheritance overriding

我在 java 项目中有一个继承的对象,我试图调用子对象中的重写方法。由于某种原因,正在调用该方法的父版本。我对多态性的理解是,总是调用方法的最低版本。为什么调用父版本?

public class Generator
{
    public static void acceptPending()
    {
        System.out.println("top level is called");
    }
}

public class GeneratorNeo extends Generator
{
    public static void acceptPending()
    {
        System.out.println("neo level is called");
    }
}

public class Driver()
{
    public static void main(String[] args)
    {
        Generator gen = null;
        gen = new GeneratorNeo();
        gen.acceptPending(); // prints top level is called
    }
}
Run Code Online (Sandbox Code Playgroud)

Ahm*_*bil 5

AcceptPending是一个静态方法,静态方法是根据对象的编译时类型(即Parent类型)来调用的。与实例方法不同。

因此,从两个类中删除 static 关键字将为您提供预期的行为。