实例引用如何访问静态方法?

时间:2019-06-14 13:50:02

标签: java overriding static-methods

public class StaticOverrideTest {
    public static void main(String args[]) {
        Parent p = new Parent();
        p.name();   

        p = new Child();
        p.name();  

        Child c = new Child();
        c.name();        
    }
}

class Parent{  
    public static void name(){
        System.out.println("static method from Parent");
    }
}

class Child extends Parent{       
    public static void name(){
        System.out.println("static method from Child");
    }
}

输出

static method from Parent
static method from Parent
static method from Child

理想情况下,我们不应通过引用实例来调用静态方法,但在此代码中我们正在使用它,但它仍然可以正常工作。

0 个答案:

没有答案