当前位置: 技术问答>java相关
关于构建器问题?
来源: 互联网 发布时间:2015-10-11
本文导语: public class Company{ public Company(){ System.out.println("Company: 0"); } public Company(int i){ this(); System.out.println("Company: 1"); } public static void main(String args[]){ Research s=new Research(); Research r=new Research(1999); } } class...
public class Company{
public Company(){
System.out.println("Company: 0");
}
public Company(int i){
this();
System.out.println("Company: 1");
}
public static void main(String args[]){
Research s=new Research();
Research r=new Research(1999);
}
}
class Research extends Company{
public Research(){
System.out.println("Research: 0");
}
public Research(int i){
System.out.println("Research: 1");
}
}
为什么输出是:
Company:0
Research:0
Company:0
Research:1
而不是:
Company:0
Research:0
Company:0
Company:1(这里是因为Company(int i)调用了this()方法)
Research:1
public Company(){
System.out.println("Company: 0");
}
public Company(int i){
this();
System.out.println("Company: 1");
}
public static void main(String args[]){
Research s=new Research();
Research r=new Research(1999);
}
}
class Research extends Company{
public Research(){
System.out.println("Research: 0");
}
public Research(int i){
System.out.println("Research: 1");
}
}
为什么输出是:
Company:0
Research:0
Company:0
Research:1
而不是:
Company:0
Research:0
Company:0
Company:1(这里是因为Company(int i)调用了this()方法)
Research:1
|
程序在初始化子类时先要寻找其父类的默认构造方法,如果父类定义了其他非默认构造方法却没定义默认构造方法,程序错误;解决这个的办法就是定义一个默认构造方法或在子类构造方法中第1句中调用super(i)(根据父类构造函数的形式写)。这里就是子类初始化时调用的是父类
public Company(){
System.out.println("Company: 0");
}
这个默认构造方法,并没有调用
public Company(int i){
this();
System.out.println("Company: 1");
}
public Company(){
System.out.println("Company: 0");
}
这个默认构造方法,并没有调用
public Company(int i){
this();
System.out.println("Company: 1");
}
|
子類在實例化時只能調用父類的默認構造器,也就是沒有參數的構造器,所以
new Research(1999)時,只能調用Company中的 Public Company().
new Research(1999)時,只能調用Company中的 Public Company().