今天在微信看到一个问题很有意思,代码如下:
public class Son extends Father{
SonProp sonProp=new SonProp();
public Son(){
System.out.println("Son is construct");
}
public static void main(String[] args){
new Son();//构造子类对象先要调用父类构造方法
}
}
class Father{
FatherProp fatherProp=new FatherProp();
public Father(){
System.out.println("Father is construct");//所以这句话先输出
}
}
class SonProp{
public SonProp(){
System.out.println("SonProp is construct");
}
}
class FatherProp{
public void FatherProp(){
System.out.println("FatherProp is construct");
}
}
输出的结果是:
Father is construct
SonProp is construct
Son is construct
为什么运行的顺序是这样呢?
为什么主类中创建SonProp的语句会被运行呢?
然后我又在主类中new Son();下面又加了一句Father father=new Father();结果输出中为什么没有"FatherProp is construct"这一句呢?
哪位大神可以帮忙解答下