当前位置: 代码迷 >> J2SE >> 关于构造方法的理解不是很清楚,请大家指点。解决方法
  详细解决方案

关于构造方法的理解不是很清楚,请大家指点。解决方法

热度:101   发布时间:2016-04-24 14:31:08.0
关于构造方法的理解不是很清楚,请大家指点。
public   class   Test
{
public   static   void   main(String   args[])
{
Person   p1   =   new   Person( "A ");
Person   p2   =   new   Person( "B ",   "Shanghai ");
Student   s1   =   new   Student( "C ",   "S1 ");
Student   s2   =   new   Student( "D ",   "Shanghai ",   "S2 ");
System.out.println(p1.info());
System.out.println(p2.info());
System.out.println(s1.info());
System.out.println(s2.info());
}
}

class   Person
{
private   String   name;
private   String   location;

Person(String   name)
{
this.name   =   name;
location   =   "Beijing ";
}

Person(String   name,   String   location)
{
this.name   =   name;
this.location   =   location;
}

public   String   info()
{
return   "name:   "   +   name   +   "   location:   "   +   location;
}
}

class   Student   extends   Person
{
private   String   school;
Student(String   name,   String   school)
{
this(name,   "Beijing ",   school);
}
Student(String   n,   String   l,   String   school)
{
super(n,   l);
this.school   =   school;
}
public   String   info()
{
return   super.info()   +   "   school:   "   +   school;
}
}

程序很简单,但是有一点我不明白,就是在初始化子类的时候不是要先调用父类的构造方法吗?如果没有显式调用,那么系统自动调用默认的不带参数的构造方法。可是Student   s1   =   new   Student( "C ",   "S1 ");这句执行的时候它的构造方法中没有显式的调用父类的构造方法,且父类中也没有不带参数的构造方法,那么为什么不会出现错误?不解。

------解决方案--------------------
会不会先执行this(name, "Beijing ", school);这里,然后才会去想父类的构造呢?

------解决方案--------------------
编译器会调用与子类参数相同的基类构造器
Student(String n, String l, String school)
{
super(n, l);
this.school = school;
}
在这之中,由于基类没有这样的构造器,所以你必须显式的调用一个父类构造器,不信你把super去掉。
Student(String name, String school)
{
System.out.println( "AAA ");
this(name, "Beijing ", school);
}但在这之中,它执行的时候实际上是这样的
Student(String name, String school)
{
super(name,school);
System.out.println( "AAA ");
this(name, "Beijing ", school);
}
所以为什么你说会调用无参构造器,是因为你的构造器无参,如果你的构造器有参,那也会调用有参构造器

------解决方案--------------------
调试跟踪一下
------解决方案--------------------
留名
  相关解决方案