当在子类中重写静态方法时,我对它的行为感到困惑.
以下是代码:
public class SuperClass {
public static void staticMethod() {
System.out.println("SuperClass: inside staticMethod");
}
}
public class SubClass extends SuperClass {
//overriding the static method
public static void staticMethod() {
System.out.println("SubClass: inside staticMethod");
}
}
public class CheckClass {
public static void main(String[] args) {
SuperClass superClassWithSuperCons = new SuperClass();
SuperClass superClassWithSubCons = new SubClass();
SubClass subClassWithSubCons = new SubClass();
superClassWithSuperCons.staticMethod();
superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();
}
}
Below is the output which we are getting :
1) SuperClass: inside staticMethod
2) SuperClass: inside staticMethod
3) SubClass: inside staticMethod
为什么在第二种情况下会调用超类的静态方法?
如果方法不是静态的,那么根据多态性,在运行时传递子类对象时会调用子类的方法.