this和super用法的总结
2016-02-14 14:16
513 查看
this和super用法的总结
1、 this的作用:
(1) 可以用于在类的构造器中调用该类的属性值,如对参数初始化等;
(2) 在一个构造器中调用另一个构造器,在构造器中调用另一个构造器,如this(),
(3) this只能用在构造器中,且必须置于首行,否则会提示错误:Constructor call must be the first statement in a constructor.
注意需要将this()置于首行;
例子:
四个构造器,其中第一个构造器是默认构造器,对property和attribute进行初始化。第二个构造器对attribute进行初始化。第三个构造器使用this()调用了第一个构造器,在使用第三个构造器新建一个对象时,需要用第一个构造器对类属性进行初始化。第四个构造器调用第二个构造器。
1、 this的作用:
(1) 可以用于在类的构造器中调用该类的属性值,如对参数初始化等;
(2) 在一个构造器中调用另一个构造器,在构造器中调用另一个构造器,如this(),
(3) this只能用在构造器中,且必须置于首行,否则会提示错误:Constructor call must be the first statement in a constructor.
注意需要将this()置于首行;
例子:
public class ThisAndSuper{ <span style="white-space:pre"> </span>int property; <span style="white-space:pre"> </span>String attribute; <span style="white-space:pre"> </span>public ThisAndSuper(){ <span style="white-space:pre"> </span>property = 1; attribute = "constuctor1"; } public ThisAndSuper(String attribute){ this.attribute = attribute; } public ThisAndSuper(float test){ this(); //调用第一个构造器 } public ThisAndSuper(double test){ this("what"); //调用第二个构造器 } public static void main(String args[]){ ThisAndSuper thisAndSuper = new ThisAndSuper(); ThisAndSuper thisAndSuper2 = new ThisAndSuper("are"); System.out.println(thisAndSuper.attribute + " " + thisAndSuper.property); System.out.println(thisAndSuper2.attribute + " " + thisAndSuper.property); } } // output: // constuctor1 1 // are 0
四个构造器,其中第一个构造器是默认构造器,对property和attribute进行初始化。第二个构造器对attribute进行初始化。第三个构造器使用this()调用了第一个构造器,在使用第三个构造器新建一个对象时,需要用第一个构造器对类属性进行初始化。第四个构造器调用第二个构造器。
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树