abstract class Person{
public Person(){
this.print();
}
public abstract void print();
}
class Students extends Person{
private int score = 100;
public Students(int score){
this.score = score;
}
public void print(){
System.out.println(" score = "+ score);
}
}
public class Demo {
public static void main(String[] args){
Person per = new Students(68);
}
}这个程序的分析思路?
public Person(){
this.print();
}
public abstract void print();
}
class Students extends Person{
private int score = 100;
public Students(int score){
this.score = score;
}
public void print(){
System.out.println(" score = "+ score);
}
}
public class Demo {
public static void main(String[] args){
Person per = new Students(68);
}
}这个程序的分析思路?
期待详解。
Students 中score不是有默认值100吗?为什么不是100而是int型的默认值0呢。
public class JastTest {
public static void main(String[] args){
Person per = new Students(68);
per.print();
}
}
abstract class Person{
public Person(){
System.out.println("Person init...");
this.print();
}
public abstract void print();
}
class Students extends Person{
private int score = 100;
public Students(int score){
System.out.println("Students init...score now is "+this.score);
this.score = score;
}
public void print(){
System.out.println(" score = "+ score);
}
}运行结果是:
Person init...
score = 0
Students init...score now is 100
score = 68
Students 中score不是有默认值100吗?为什么不是100而是int型的默认值0呢。打印的时候Students还没执行初始化呢,所以score是int型的默认值0;
1.类的初始化顺序
父类的静态变量 和 父类的静态代码块 -> 子类的静态成员 和 子类的静态代码块 -> 父类的成员变量 和 父类的代码块 -> 父类的构造函数 -> 子类的成员变量 和 子类的代码块 -> 子类的构造函数你这个代码中, 父类与子类都不存在静态成员, 所以第一件事, 就是调用父类的构造函数2.RTTI(运行时类型检测), JVM会在程序运行的时, 使用反射机制获得类的真实类型, 具体关于反射原理你可以自己百度查.所以当执行父类的构造函数中this.print(); 这句代码时, JVM知道当前句柄所对应的类的真实类型为Students类, 而Students类中恰好重写了print()这个方法, 所以JVM就会调用Students类中的print()方法, 但此时Students类的对象尚未被初始化, 所以对于int类型的变量score就是用的默认的初始化值0。所以你得到输出结果就是0。 归根结底其实就是多态.另外多说一句, 构造函数的使用原则是, 尽可能简单的使类进入到就绪状态, 避免调用任何方法, 如果非要调用, 那么最好调用final方法. 具体的你可以看看<<thinking in java>>
呵呵·我之前也碰到过这样的问题。学习了,谢谢楼主分享。
期待详解。