ฉันต้องการแบ่งปันสิ่งที่ฉันเข้าใจจากคำหลักนี้ คำหลักนี้มี 6 จาวาในจาวาดังนี้: -
1. สามารถใช้อ้างถึงตัวแปรคลาสปัจจุบัน
ให้เราเข้าใจด้วยรหัส *
มาทำความเข้าใจกับปัญหาหากเราไม่ใช้คำค้นหานี้ตามตัวอย่างที่ให้ไว้ด้านล่าง:
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
id_no = id_no;
name=name;
salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
เอาท์พุท: -
0 null 0.0
0 null 0.0
ในตัวอย่างข้างต้นพารามิเตอร์ (อาร์กิวเมนต์ที่เป็นทางการ) และตัวแปรอินสแตนซ์เหมือนกัน ดังนั้นเราจึงใช้คำหลักนี้เพื่อแยกแยะตัวแปรท้องถิ่นและตัวแปรอินสแตนซ์
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
this.id_no = id_no;
this.name=name;
this.salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
เอาท์พุท:
111 ankit 5000
112 sumit 6000
2. เพื่อเรียกใช้เมธอดคลาสปัจจุบัน
class A{
void m(){System.out.println("hello Mandy");}
void n(){
System.out.println("hello Natasha");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
เอาท์พุท:
hello Natasha
hello Mandy
3. เพื่อเรียกใช้ตัวสร้างคลาสปัจจุบัน มันถูกใช้เพื่อสร้างการผูกมัด
class A{
A(){System.out.println("hello ABCD");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
เอาท์พุท:
hello ABCD
10
4. ผ่านเป็นอาร์กิวเมนต์ในวิธีการ
class S2{
void m(S2 obj){
System.out.println("The method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
เอาท์พุท:
The method is invoked
5. ผ่านเป็นอาร์กิวเมนต์ในการเรียกตัวสร้าง
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. เพื่อส่งคืนอินสแตนซ์ของคลาสปัจจุบัน
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
เอาท์พุท: -
Hello
นอกจากนี้คำหลักนี้ไม่สามารถใช้งานได้หากไม่มี (dot) เนื่องจากเป็นไวยากรณ์ที่ไม่ถูกต้อง