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