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[]){ } }
相关文章推荐
- UVALive - 3211 Now or later (2-SAT)
- PHP 无限分类三种方式,非函数的递归调用![兄弟连]
- JS小结
- base64生成PDF文件
- vxWorks 命令
- 指针与数组用法笔记
- 黑客成长之路-----十问(第一天)
- SVG实现圆环loading进度效果实例页面
- HEVC码率控制算法研究与HM相应代码分析(一)——HEVC标准及编码流程介绍
- list,map,set,array的特点和相互转换
- hibernate学习系列-----(6)hibernate对集合属性的操作之Set集合篇
- java反射获取注解并拼接sql语句
- c#操作附加数据库的方法
- Apache如何每天生成独立日志文件(access_log和error_log)
- adb停止工作解决
- 在开发板上挂载NFS
- hdu5361 In Touch 神奇的dij,神奇的写法
- Tomcat无法shutdown进程问题解决办法
- libuv(不断更新)
- Android studio internal http server disabled