this使用原文
可以区分对象中的成员变量及传进来的参数。比如在对象的成员名称与参数名字相同时,如果直接使用变量名的话,会被编译器认为是对传进来的参数进行操作,但是加上this后就可以对对象的成员变量进行操作了。Eg:
public class Hello { String s = "Hello"; public Hello(String s){ System.out.println("s = " + s); System.out.println("1 -> this.s = " + this.s); this.s = s; System.out.println("2 -> this.s = " + this.s); } public static void main(String[] args) { Hello x=new Hello("HelloWorld!"); } } 运行结果:s = HelloWorld! 这里s为传进去的参数 1 -> this.s = Hello 这个即为Hello的成员变量s 2 -> this.s = HelloWorld! 这里s是将参数传给成员变量Hello.s即是说调用当前对象的方法,而不是外部的对象的方法,这里强调的是使用的是当前操作的对象的方法。 Eg:
class A { public A() { new B(this).print(); //此处this是把A类对象作为参数传给B中方法B,其即为B(A) } public void print() { System.out.println("Hello from A!"); } } //B对象 class B { A a; public B(A a) { this.a = a; //将形参a传给B.a } //B对象的方法 public void print() { a.print(); System.out.println("Hello from B!"); } } public class This { public static void main(String []args) { new B(new A()); } } 运行结果: Hello from A! A.print()的结果 Hello from B! B.print()的结果用到一些内部类和匿名。当在匿名类中用this时,这个this则指的是匿名类或内部类本身。这时如果我们要使用外部类的方法和变量的话,则应该加上外部类的类名。 Eg:
class A{ int i = 1; public A() { Thread thread = new Thread() { public void run() { for(;;) { A.this.run(); //这里是指创建A类对象的run方法 try { sleep(1000); } catch(InterruptedException ie) { } } } }; //注意这里有; 这里创建的一个对象thread thread.start(); } public void run() { System.out.println("i = " + i); i++; } } public class This { public static void main(String[] args) throws Exception { new A(); } } 运行结果: i = 1 每隔一秒i+1输出.....Eg:
class Flower{ Flower (int petals){ System.out.print(petals); } Flower(String ss){ System.out.println(ss); } Flower(int petals, String ss){ //petals++;调用另一个构造函数的语句必须在最起始的位置 this(petals); //this(ss);会产生错误,因为在一个构造函数中只能调用一个构造函数 } } public class This { public static void main(String []args) { new Flower(3,"hcusdhfuchdhcf"); } } 运行结果: 3值得注意的是: 1.在构造调用另一个构造函数,调用动作必须置于最起始的位置。 2.不能在构造函数以外的任何函数内调用构造函数。 3.在一个构造函数内只能调用一个构造函数。