您的位置:首页 > 其它

Constructor call must be the first statement in a constructor

2015-08-08 11:45 274 查看


super()和this ()不能共存,否则编译时会报异常。
Constructorcall must be the first statement in a constructor

换句话说就是super()和this()都必须在构造方法的第一行。

this(有参数/无参数) 用于调用本类相应的构造函数

super(有参数/无参数) 用于调用父类相应的构造函数

而且在构造函数中,调用必须写在构造函数定义的第一行,不能在构造函数的后面使用。

一个构造函数定义中不能同时包括this调用和super调用,如果想同时包括的话,可以在this()调用的那个构造函数中首先进行super()调用。也可以把TestB()这个方法修改成非构造方法,在构造方法TestB(int i)中调用。



正确解释:The parent class' constructor needs to becalled before the subclass' constructor. This will ensure that if you call anymethods on the parent class in your constructor, the parent class has alreadybeen set up correctly.

翻译:之前父类的构造函数需要调用子类的构造函数。这将确保如果你调用任何方法在父类构造函数,父类已经被正确设置。

2.错误:Implicit super constructor xx()
is undefined for default constructor. Must define an explicit constructor

因为你的父类已经定义了一个有参的构造函数,此时编译器不会为你调用默认的构造函数,

当子类继承时,必须在自己的构造函数显式调用父类的构造函数,自己才能确保子类在初始化前父类会被实例化,

如果你父类中有无参的构造函数,子类就不会强制要求调用,即你写的那个就可以通过,

编译器会默认帮你调用父类的构造函数。

按原来的思路,必须该成下面的:

class Person { 
	protected String name; 
	protected int age; 
	//你已经定义了自动的构造函数,此时编译器不会为你创建默认的构造函数 
	public Person(String name,int age) { 
		this.name=name; 
		this.age=age; 
	} 
	public void print() { 
		System.out.println("Name:"+name+"/nAge:"+age); 
	}
} 
/*由于父类的构造函数是有参的,所以编译不会为你自动调用默认的构造函数,此时,子类在自己的构造函数中必须显式的调用父类的构造函数 */
class Student extends Person { 
	public Student(){      //子类构造函数 
	//super();   不行,因为你的父类没有无参的构造函数 
	
	super("a",1); 
      //显示调用父类的构造函数,而且必须是第一行调用 
	} 
} 
	class Test { 
		public static void main(String args[]){ 
		} 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: