码迷,mamicode.com
首页 > 其他好文 > 详细

Constructor call must be the first statement in a constructor

时间:2017-05-31 22:21:01      阅读:347      评论:0      收藏:0      [点我收藏+]

标签:编译   read   ica   子类   技术分享   16px   初始化   不能   ensure   

技术分享

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[]){ 
		} 
}



Constructor call must be the first statement in a constructor

标签:编译   read   ica   子类   技术分享   16px   初始化   不能   ensure   

原文地址:http://www.cnblogs.com/liguangsunls/p/6926038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!