您的位置:首页 > 编程语言 > Java开发

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()置于首行;

例子:

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 编程 this super