Java学习笔记——this
this关键字被隐式的用语引用对象的成员变量和方法,如下下面一段程序中:
private void setName(String name) { this.name=name; }
其中,方法中的形参name和类中的成员变量name重名了,那么便可以利用this.name指定类中的成员变量。即this可以调用成员变量和成员方法。返回方法如下程序所示:
public Bird getBird(){ return this; }
方法的返回值是Bird类,所以方法体中使用return this将Bird的对象进行返回。对象返回还可以这样用:
public class Leaf{ int i = 0; Leaf increment(){ i++; return this; } public static void main(String[] args) { Leaf x = new Leaf(); x.increment().increment().increment(); } }
同时,当在构造器中调用构造器,需要用到this。有时候为一个类写了多个构造器,有时候会在一个构造器中调用另外一个构造器,以避免重复代码。可以用this关键字做到。通常this指的是这个对象或者当前对象,而且他本身表示对当前对象的引用。在构造器中,如果为this添加了参数列表,那么便具有不同的含义。可以实现构造器之间的调用。
package test; public class TestThis { int count = 0; String s = "initial value"; TestThis(int petals) { // TODO Auto-generated constructor stub count = petals; System.out.println("Constructor int only,count="+petals); } TestThis(String ss) { // TODO Auto-generated constructor stub System.out.println("Constructor String only,s="+ss); } TestThis(String s,int petals) { // TODO Auto-generated constructor stub this(petals); this.s=s; System.out.println("int & String"); } TestThis() { // TODO Auto-generated constructor stub this("hi", 11); System.out.println("default"); } void printPetalCount(){ System.out.println("count= "+count+" s="+s); } public static void main(String[] args) { // TODO Auto-generated method stub TestThis x = new TestThis(); x.printPetalCount(); } }

浙公网安备 33010602011771号