样题一:
class P {
private int val = 10;
public void output() {
System.out.println("P.output(),val+" + val);
}
public P() {
System.out.println("P constructor");
output();
}
}
public class A extends P {
private int val = 1;
public void output() {
System.out.println("A.output(),val=" + val);
}
public A(int val) {
this.val = val;
System.out.println("A constructor");
}
public static void main(String[] args) {
A a = new A(5);
}
}
答案:P constructor A.output(),val=0 A constructor
样题二:
class parent {
public parent() {
System.out.println("parent...");
}
}
class child extends parent {
brother b = new brother();
public child() {
System.out.println("child...");
}
}
class brother {
public brother() {
System.out.println("brother...");
}
}
public class Testchild {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(new child());
}
}
答案:parent... brother... child...
结论:属性的优先级高于方法,父类构造方法高于自身构造方法,重写父亲类的方法高于本身属性执行 。