Java this keyword

await 2021-09-15 07:19:36
java keyword


this Keywords are used to represent the current object itself , Or an instance of the current class , adopt this You can call all the methods and properties of this object . for example : public class Demo{

public int x = 10;
public int y = 15;
public void sum(){
// adopt this Click the member variable
int z = this.x + this.y;
System.out.println("x + y = " + z);
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.sum();
}

} Running results : x + y = 25

In the program above ,obj yes Demo An instance of a class ,this And obj Equivalent , perform int z = this.x + this.y;, It's like execution int z = obj.x + obj.y;.

Be careful :this It makes sense only after the class is instantiated . Use this Distinguish variables with the same name When a member variable has the same name as a variable inside a method , You want to call a member variable inside a method , What shall I do? ? You can only use this, for example : public class Demo{

public String name;
public int age;
public Demo(String name, int age){
this.name = name;
this.age = age;
}
public void say(){
System.out.println(" What is the name of the website " + name + ", It has been established " + age + " year ");
}
public static void main(String[] args) {
Demo obj = new Demo(" Micro school ", 3);
obj.say();
}

} Running results : The name of the website is weixueyuan , It has been established 3 year

The scope of the formal parameter is the whole method body , It's a local variable . stay Demo() in , Formal parameter and member variable have the same name , If not used this, Access to local variables name and age, Instead of member variables . stay say() in , We didn't use this, Because the scope of the member variable is the entire instance , Of course, you can add this: public void say(){

System.out.println(" What is the name of the website " + this.name + ", It has been established " + this.age + " year ");

} Java By default, all member variables and member methods are associated with this Link together , Therefore use this In some cases, it is redundant . Initialize the object as the method name That is to say, it is equivalent to calling other construction methods of this class , It has to be the first sentence of the construction method . Examples are as follows : public class Demo{

public String name;
public int age;
public Demo(){
this(" Micro school ", 3);
}
public Demo(String name, int age){
this.name = name;
this.age = age;
}
public void say(){
System.out.println(" What is the name of the website " + name + ", It has been established " + age + " year ");
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.say();
}

} Running results : The name of the website is weixueyuan , It has been established 3 year

It is worth noting that : Another construction method is called in the construction method , The calling action must be placed in the most initial position . Constructor cannot be called inside any method other than constructor . Only one constructor can be called within a constructor .

The above code involves method overloading , namely Java Multiple methods with the same name are allowed , As long as the parameters are different . The following chapters will explain . Pass as a parameter You need to call a method in some completely separated classes , And pass a reference to the current object as a parameter . for example : public class Demo{

public static void main(String[] args){
B b = new B(new A());
}

}

class A{

public A(){
new B(this).print(); // Anonymous object
}
public void print(){
System.out.println("Hello from A!");
}

}

class B{

A a;
public B(A a){
this.a = a;
}
public void print() {
a.print();
System.out.println("Hello from B!");
}

} Running results : Hello from A! Hello from B!

An anonymous object is an object without a name . If the object is used only once , It can be used as an anonymous object , In the code new B(this).print(); Equivalent to ( new B(this) ).print();, Through the first new B(this) Create an object without a name , Call its method again .this Keywords are used to represent the current object itself , Or an instance of the current class , adopt this You can call all the methods and properties of this object . for example : public class Demo{

public int x = 10;
public int y = 15;
public void sum(){
// adopt this Click the member variable
int z = this.x + this.y;
System.out.println("x + y = " + z);
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.sum();
}

} Running results : x + y = 25

In the program above ,obj yes Demo An instance of a class ,this And obj Equivalent , perform int z = this.x + this.y;, It's like execution int z = obj.x + obj.y;.

Be careful :this It makes sense only after the class is instantiated . Use this Distinguish variables with the same name When a member variable has the same name as a variable inside a method , You want to call a member variable inside a method , What shall I do? ? You can only use this, for example : public class Demo{

public String name;
public int age;
public Demo(String name, int age){
this.name = name;
this.age = age;
}
public void say(){
System.out.println(" What is the name of the website " + name + ", It has been established " + age + " year ");
}
public static void main(String[] args) {
Demo obj = new Demo(" Micro school ", 3);
obj.say();
}

} Running results : The name of the website is weixueyuan , It has been established 3 year

The scope of the formal parameter is the whole method body , It's a local variable . stay Demo() in , Formal parameter and member variable have the same name , If not used this, Access to local variables name and age, Instead of member variables . stay say() in , We didn't use this, Because the scope of the member variable is the entire instance , Of course, you can add this: public void say(){

System.out.println(" What is the name of the website " + this.name + ", It has been established " + this.age + " year ");

} Java By default, all member variables and member methods are associated with this Link together , Therefore use this In some cases, it is redundant . Initialize the object as the method name That is to say, it is equivalent to calling other construction methods of this class , It has to be the first sentence of the construction method . Examples are as follows : public class Demo{

public String name;
public int age;
public Demo(){
this(" Micro school ", 3);
}
public Demo(String name, int age){
this.name = name;
this.age = age;
}
public void say(){
System.out.println(" What is the name of the website " + name + ", It has been established " + age + " year ");
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.say();
}

} Running results : The name of the website is weixueyuan , It has been established 3 year

It is worth noting that : Another construction method is called in the construction method , The calling action must be placed in the most initial position . Constructor cannot be called inside any method other than constructor . Only one constructor can be called within a constructor .

The above code involves method overloading , namely Java Multiple methods with the same name are allowed , As long as the parameters are different . The following chapters will explain . Pass as a parameter You need to call a method in some completely separated classes , And pass a reference to the current object as a parameter . for example : public class Demo{

public static void main(String[] args){
B b = new B(new A());
}

}

class A{

public A(){
new B(this).print(); // Anonymous object
}
public void print(){
System.out.println("Hello from A!");
}

}

class B{

A a;
public B(A a){
this.a = a;
}
public void print() {
a.print();
System.out.println("Hello from B!");
}

} Running results : Hello from A! Hello from B!

An anonymous object is an object without a name . If the object is used only once , It can be used as an anonymous object , In the code new B(this).print(); Equivalent to ( new B(this) ).print();, Through the first new B(this) Create an object without a name , Call its method again .

This article altogether 1204 Number of words , Average reading time ≈ 4 minute

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[await]所创,转载请带上原文链接,感谢
https://javamana.com/2021/09/20210909125824190f.html

  1. 别再说你不会JVM性能监控和调优了,2021华为Java高级面试题及答案,
  2. 15 useful cron work examples commonly used by Senior Linux system administrators
  3. Ne dites pas que vous ne pouvez pas surveiller et ajuster les performances JVM, 2021 Huawei Java Advanced interview Questions and Answers,
  4. 別再說你不會JVM性能監控和調優了,2021華為Java高級面試題及答案,
  5. 十多家大厂Java面试真题锦集干货整理,Java开发者该学习哪些东西提高竞争力?
  6. 十分钟带你回顾Spring常问的知识点,35岁老年程序员的绝地翻身之路,
  7. 区区一个SpringBoot问题就被干趴下了,看完这一篇就够了!
  8. K8s gestion des ressources (opérations de base)
  9. Java and cloud native dating
  10. 區區一個SpringBoot問題就被幹趴下了,看完這一篇就够了!
  11. Un problème de démarrage de printemps dans le district a été séché, et c'est assez!
  12. Dix minutes pour vous faire passer en revue les points de connaissance que Spring demande souvent, le chemin du retour Jedi d'un programmeur âgé de 35 ans,
  13. Plus d'une douzaine de grandes usines Java interview vrai sujet brocade collection de marchandises sèches, les développeurs Java devraient apprendre ce qui améliore la compétitivité?
  14. 十分鐘帶你回顧Spring常問的知識點,35歲老年程序員的絕地翻身之路,
  15. Guide de route d'apprentissage Java, redis a plusieurs types de données?
  16. 华为Java高级工程师面试题,字节跳动上千道精选面试题还不刷起来!
  17. 华为Java面试题目,腾讯Java开发面试记录,
  18. Propriétés et méthodes des objets Array en javascript!,Pseudo - classes et pseudo - éléments pour CSS
  19. Design pattern -- agent pattern
  20. 華為Java面試題目,騰訊Java開發面試記錄,
  21. Huawei Java interview title, Tencent Java Development interview record,
  22. Huawei Java Senior Engineer interview question, Byte Jumping thousand Selected Interview Question is still not Brushed!
  23. 双非本科字节跳动Java面试题分享,一篇文章教你搞定计算机网络面试,
  24. 又到一年金三银四,2021最新Java笔试题及答案,
  25. Huawei Finance and Economics 2021 Spring Recruitment interview, what is distributed Lock?Pourquoi utiliser des serrures distribuées?
  26. Un an plus tard, Golden, Silver, Silver, and Silver, 2021, the latest Java written Examination Questions and Answers,
  27. Partage de questions d'entrevue Java à double saut d'octets non - premier cycle, un article vous apprend à gérer l'entrevue réseau informatique,
  28. Computer graduation project java online voting system based on SSM
  29. K8s gestion des ressources (opérations de base)
  30. 又到一年金三銀四,2021最新Java筆試題及答案,
  31. Collection de code de base JavaScript (1)
  32. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  33. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  34. Cloud Security Daily 210914: Red Hat Jboss Middleware Platform found important Security Vulnerability and needs to be upgraded as soon as possible
  35. 吐血整理,腾讯团队实力打造spring入门教程,
  36. 史上最全的微服务专业术语面试50问,字节跳动Java岗经典面试真题,
  37. Absolument!C'est l'analyse la plus détaillée du code source de hashtap que j'ai jamais vu!
  38. Computer graduation project Java logistics order management system of logistics company based on SSM
  39. Talk about Kafka: source code analysis of producer
  40. [springboot2 starts from 0] development tips - Lombok, devtools, spring initailizr
  41. 国内一线互联网公司面试题汇总,2021年大厂Java岗面试必问,
  42. 啃完吃透保你涨薪5K,熬夜整理小米Java面试题,
  43. 和字节跳动大佬的技术面谈,Redis成神之路电子版教程已问世,
  44. Le terme professionnel le plus complet de l'histoire des micro - services interview 50 questions, Byte Jumping Java post Classic interview vrai problème,
  45. After using mybatisplus, I haven't written SQL for a long time
  46. [springboot2 starts from 0] how to write a springboot application?
  47. Huawei cloud guassdb (for redis) released a new version, and the two core features were officially unveiled
  48. 和字節跳動大佬的技術面談,Redis成神之路電子版教程已問世,
  49. 啃完吃透保你漲薪5K,熬夜整理小米Java面試題,
  50. Avec l'interview technique du gigolo, le tutoriel électronique redis est sorti.
  51. Après avoir mangé, assurez - vous d'augmenter votre salaire de 5K et de rester debout tard pour trier les questions d'entrevue Java de millet.
  52. Résumé des questions d'entrevue pour les entreprises Internet nationales de première ligne, qui doivent être posées lors de l'entrevue d'emploi Java de la grande usine en 2021,
  53. Le tri des crachats de sang, la force de l'équipe Tencent pour créer le tutoriel d'introduction au printemps,
  54. Java and scala concurrency Fundamentals
  55. Analysis of java thread source code based on Hotspot
  56. 國內一線互聯網公司面試題匯總,2021年大廠Java崗面試必問,
  57. Introduction au module de contrôle de Connexion MySQL
  58. 大厂高级测试面试题,Java面试基础技能罗列,
  59. Comprendre l'architecture sous - jacente d'InnoDB en exécutant une instruction
  60. Chargeur de classe 1 Tomcat