代码如下:
在主函数中先new Student();由于它继承Person,所以会先调用Person的构造方法,所以不应该输出aa吗?为什么是输出bb呢?请教
public class hello {
public static void main(String[] args){
new Student() ;
new Person();
}
}
class Person{
static String str= "aa";
public Person(){
this.show();
}
public void show(){
System.out.println(this.str);
}
}
class Student extends Person{
static private String str = "bb";
@Override
public void show() {
System.out.println(str);
}
}
debugger一下,你就知道了,因为你在子类中重写了父类的show,所以实际是在父类构造函数中调用了show,但是起作用的是子类的show方法,因为重写了的原因。所以打印的就是子类的str,即bb