什么时候会用到this()构造方法?
2016-03-24 16:21
337 查看
Where to use this() constructor call?
The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let’s see the example given below that displays the actual use of this keyword.
output:
110 Henry null
110 Berlin Germany
Rule: Call to this() must be the first statement in constructor.
compiler will be warning:
Constructor call must be the first statement in a constructor.
The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let’s see the example given below that displays the actual use of this keyword.
package com.hotmail.henrytien; public class Student14 { int id; String name; String city; public Student14(int id,String name) { this.id = id; this.name = name; } public Student14(int id,String name, String city) { this(id, name); this.city = city; } void display() { System.out.println(id + " "+ name + " " + city); } public static void main(String[] args) { // TODO Auto-generated method stub Student14 s1 = new Student14(110,"Henry"); Student14 s2 = new Student14(110,"Berlin","Germany"); s1.display(); s2.display(); } }
output:
110 Henry null
110 Berlin Germany
Rule: Call to this() must be the first statement in constructor.
compiler will be warning:
Constructor call must be the first statement in a constructor.
相关文章推荐
- Parsing error
- angularJS controller 控制器获取控制父级标签
- 三层架构和MVC
- SqlServer2008到期升级企业版 密钥+图解
- 阿里巴巴面试题
- Class not found 解决方法,找不到主类解决方法,eclipse
- signalR 实现简单聊天
- 自定义View实现类似QQ图片上传的效果
- Durandal开发起航
- 视频压缩编码和音频压缩编码的基本原理
- 内存分配与回收策略
- GC的触发时间
- 《windows程序设计(C语言版)》笔记
- 【matlab】:matlab中如何三维画球?
- java final 关键字
- document.getElementById方法在火狐和谷歌浏览器兼容
- net-snmp添加自定义MIB
- exe4j打包jar文件为exe文件出现的问题:The JAVA_HOME environment variable does not point to a working 32-bit JDK or JRE.
- 按条件模糊查询及分页查询
- 数据库面试常问的一些基本概念