Java中的this指针
在Java中,提到this谁都不会陌生,这里再简单整理下。备忘。
Java中,一般来说this指针指的是当前正在訪问的这段代码的对象,可是假设在内部类中须要使用外部类中的对象。这时就须要使用外部类的类名进行限定。这样的方式在Android开发中也比較常见。
package twlkyao; public class A { public A() { Inner inner = new Inner(); inner.outer(); // call the inner class's outer method. this.outer(); // call A's outer method. } public void outer() { System.out.println("outer run"); } class Inner { public void outer(){ System.out.println("inner run"); A.this.outer(); // call A's outer method. System.out.println("--------"); } } public static void main(String[] args) { A a = new A(); } }
Inner是内部类,訪问类A中的outer()方法,又因为匿名内部类中有相同的方法,所以须要使用A的this指针进行限定。
输出结果为:
inner run
outer run
--------
outer run
另外,在构造方法中。常常使用this(參数表)来调用參数多的构造方法(和Swift中的convenience initializer相似,在Swift中,convenience initializer必须调用或者说代理给designated initializer),而且Java要求在构造方法中,this(參数表)要出如今不论什么其它语句之前。
public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public Circle() { this(1.0); // call the upper initializer. this.radius = 2.0; // just to indicate that the this(parameters...) must be called first. } }
在如上代码中,无參构造函数,调用有參构造函数。在无參构造函数中再次改动radius仅仅是为了说明在构造方法中,this(參数表)要出如今不论什么其它语句之前。
參考资料:
http://bbs.csdn.net/topics/260050701
《Java语言程序设计——基础篇》