阅读时间: 10分钟
this会用在以下6种方式:
1, 它可以调用目前所在的class的instance variable。
目的是让程式去区分instance variables和parameters。
例子: 当没有使this关键字的情况下
class Student{ int rollno; String name; float fee; Student(int rollno,String name,float fee){ rollno=rollno; name=name; fee=fee; } void display(){System.out.println(rollno+" "+name+" "+fee);} } class TestThis1{ public static void main(String args[]){ Student s1=new Student(111,"martin",5000f); Student s2=new Student(112,"yeung",6000f); s1.display(); s2.display(); }}
结果是:
0 null 0.00 null 0.0
例子: 有使this关键字的情况下
class Student{ int rollno; String name; float fee; Student(int rollno,String name,float fee){ this.rollno=rollno; this.name=name; this.fee=fee; } void display(){System.out.println(rollno+" "+name+" "+fee);} } class TestThis2{ public static void main(String args[]){ Student s1=new Student(111,"martin",5000f); Student s2=new Student(112,"yeung",6000f); s1.display(); s2.display(); }}
结果是:
111 martin 5000112 yeung 6000
2, 它可以调用目前所在的class的method。
其实有没有加this关键字都是没有区别。
例子: 可以看到有加this关键字和没有加this关键字都是一样可以调用目前所在的class的method
class A{ void m(){System.out.println("hello m");} void n(){ System.out.println("hello n"); //m();//same as this.m() this.m(); } } class TestThis4{ public static void main(String args[]){ A a=new A(); a.n(); }}
结果是:
hello nhello m
3, 它可以调用目前所在的class的constructor。
可以透过this() 直接调用目前所在的class的constructor
例子:
class A{ A(){System.out.println("hello a");} A(int x){ this(); System.out.println(x); } } class TestThis5{ public static void main(String args[]){ A a=new A(10); }}
结果是:
hello a10
例子:利用this()去重用constructor
class Student{ int rollno; String name,course; float fee; Student(int rollno,String name,String course){ this.rollno=rollno; this.name=name; this.course=course; } Student(int rollno,String name,String course,float fee){ this(rollno,name,course);//reusing constructor this.fee=fee; } void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);} } class TestThis7{ public static void main(String args[]){ Student s1=new Student(111,"ankit","java"); Student s2=new Student(112,"sumit","java",6000f); s1.display(); s2.display(); }}
结果是:
111 ankit java null112 sumit java 6000
4, 它可以传递method call中的argument。
目的可以用作event handling。
例子:
class S2{ void m(S2 obj){ System.out.println("method is invoked"); } void p(){ m(this); } public static void main(String args[]){ S2 s1 = new S2(); s1.p(); } }
结果是:
method is invoked
5, 它可以传递constructor call中的argument。
当一个物件会用在不同的class时,可以利用this。
例子:
class B{ A4 obj; B(A4 obj){ this.obj=obj; } void display(){ System.out.println(obj.data);//using data member of A4 class } } class A4{ int data=10; A4(){ B b=new B(this); b.display(); } public static void main(String args[]){ A4 a=new A4(); } }
结果是:
10
6, 它可以在method中传递class的instance variable。
目的可以简化代码,只需this来完成。
例子:
class A{ A getA(){ return this; } void msg(){System.out.println("Hello java");} } class Test1{ public static void main(String args[]){ new A().getA().msg(); } }
结果是:
Hello java