如下面一段代码:
class Polymorphic{
static void method(){
System.out.println("Parent Class");
}
}class PolymorphicAndStatic extends Polymorphic{
static void method(){
System.out.println("subclass");
}
public static void main(String [] args){
Polymorphic poly = new PolymorphicAndStatic();
poly.method();
}
}
为什么只能调用到父类的方法,却不是调用到子类的方法。
class Polymorphic{
static void method(){
System.out.println("Parent Class");
}
}class PolymorphicAndStatic extends Polymorphic{
static void method(){
System.out.println("subclass");
}
public static void main(String [] args){
Polymorphic poly = new PolymorphicAndStatic();
poly.method();
}
}
为什么只能调用到父类的方法,却不是调用到子类的方法。
例如:
class Polymorphic{
static void method(){
System.out.println("Parent Class");
}
}
如果是静态的,就已经有引用,而非静态的就还没有。 public static void main(String [] args){
Polymorphic poly = new PolymorphicAndStatic();
poly.method();
}
这时候,如果super的method是非静态的,此时就只生成了子类的方法引用,而没有父类的,所以结果就是子类的,才实现了多态。否则如果已经有了父类的(静态的有了引用),就不要子类的了。
Polymorphic poly = new PolymorphicAndStatic();
poly的类类型是Polymorphic,编译的时候就定义了的。
poly.method();
这一句在编译的时候就决定了用Polymorphic的method方法。