当前位置: 技术问答>java相关
请帮帮忙吧
来源: 互联网 发布时间:2015-01-23
本文导语: public class Company { public Company() { super(); System.out.println("Company()"); } public Company(int year) { System.out.println("Company(int year)"); } public Company(int year,String loc...
public class Company
{
public Company()
{
super();
System.out.println("Company()");
}
public Company(int year)
{
System.out.println("Company(int year)");
}
public Company(int year,String location)
{
super();
System.out.println("Company(int year,String location)");
}
public static void main(String args[])
{
// System.out.println("Re1---------------------");
// Research re1 = new Research();
// System.out.println("Re2---------------------");
//Research re2 = new Research(1999);
System.out.println("Re3---------------------");
Research re3 = new Research(1999,"Dayton,ohio");
}
}
class Research extends Company
{
public Research()
{
super(1999);
System.out.println("Research()");
}
public Research(int year)
{
super(1000,"Dayton,Ohio");
System.out.println("Research(int year)");
}
public Research(int year,String location)
{
System.out.println("Research(int year,String location)");
}
}
Re3---------------------
Company()
~~~~~~~~~~为什么???
Research(int year,String location)
如何不产生Company()
{
public Company()
{
super();
System.out.println("Company()");
}
public Company(int year)
{
System.out.println("Company(int year)");
}
public Company(int year,String location)
{
super();
System.out.println("Company(int year,String location)");
}
public static void main(String args[])
{
// System.out.println("Re1---------------------");
// Research re1 = new Research();
// System.out.println("Re2---------------------");
//Research re2 = new Research(1999);
System.out.println("Re3---------------------");
Research re3 = new Research(1999,"Dayton,ohio");
}
}
class Research extends Company
{
public Research()
{
super(1999);
System.out.println("Research()");
}
public Research(int year)
{
super(1000,"Dayton,Ohio");
System.out.println("Research(int year)");
}
public Research(int year,String location)
{
System.out.println("Research(int year,String location)");
}
}
Re3---------------------
Company()
~~~~~~~~~~为什么???
Research(int year,String location)
如何不产生Company()
|
当你调用构造函数的时候,默认的情况是首先调用超类的无参构造函数。对于这一点可以作如下实验:
1.在public Company()中去掉System.out.println("Company()");
Company()就不被打印输出
2.去掉public Company()构造函数。此时编译器肯定会报错,因为
public Research(int year,String location)中没有显式调用任何父类构造函数,所以
编译器会去找父类的无参构造函数。但由于父类已经定义了有参构造函数,所以编译器不
会自动生成无参构造函数。也就是说该函数不存在,当然会报错。
1.在public Company()中去掉System.out.println("Company()");
Company()就不被打印输出
2.去掉public Company()构造函数。此时编译器肯定会报错,因为
public Research(int year,String location)中没有显式调用任何父类构造函数,所以
编译器会去找父类的无参构造函数。但由于父类已经定义了有参构造函数,所以编译器不
会自动生成无参构造函数。也就是说该函数不存在,当然会报错。