J'aimerais partager ce que j'ai compris de ce mot-clé. Ce mot-clé a 6 utilisations en java comme suit: -
1. Il peut être utilisé pour faire référence à la variable de classe actuelle.
Comprenons avec un code. *
Comprenons le problème si nous n'utilisons pas ce mot-clé par l'exemple ci-dessous:
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();
}}
Production:-
0 null 0.0
0 null 0.0
Dans l'exemple ci-dessus, les paramètres (arguments formels) et les variables d'instance sont identiques. Nous utilisons donc ce mot-clé pour distinguer la variable locale et la variable d'instance.
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();
}}
production:
111 ankit 5000
112 sumit 6000
2. Pour appeler la méthode de classe actuelle.
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();
}}
Production:
hello Natasha
hello Mandy
3. pour appeler le constructeur de classe actuel. Il est utilisé pour le chaînage des constructeurs.
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);
}}
Production:
hello ABCD
10
4. à passer comme argument dans la méthode.
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();
}
}
Production:
The method is invoked
5. passer en argument dans l'appel du constructeur
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();
}
}
Production:-
10
6. pour renvoyer l'instance de classe actuelle
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Production:-
Hello
De plus, ce mot-clé ne peut pas être utilisé sans. (Point) car sa syntaxe n'est pas valide.