this怎麼用(基礎)

this關鍵字的概述

    this關鍵字代表是對象的引用。也就是this在指向一個對象,所指向的對象就是調用該函數的對象引用。

this關鍵字作用

1. 如果存在同名成員變量與局部變量時,在方法內部默認是訪問局部變量的數據,可以通過this關鍵字指定訪問成員變量的數據。
2. 在一個構造函數中可以調用另外一個構造函數初始化對象。

例: 使用java類描述一個動物。
問題:存在同名的成員變量與局部變量時,在方法的內部訪問的是局部變量(java 採取的是就近原則的機制訪問的。)


  1. class Animal{


  2. String name ;  //成員變量


  3. String color;


  4. public Animal(String n , String c){

  5. name = n;

  6. color = c;

  7. }


  8. //this關鍵字代表了所屬函數的調用者對象

  9. public void eat(){

  10. //System.out.println("this:"+ this);

  11. String name = "老鼠"; //局部變量

  12. System.out.println(name+"在吃..."); //需求: 就要目前的name是成員變量的name.


  13. }

  14. }


  15. class Demo6

  16. {

  17. public static void main(String[] args)

  18. {

  19. Animal dog = new Animal("狗","白色");  //現在在內存中存在兩份name數據。


  20. Animal cat = new Animal("貓","黑色");

  21. cat.eat();

  22. }

  23. }

this關鍵字調用其他的構造函數要注意的事項

1. this關鍵字調用其他的構造函數時,this關鍵字必須要位於構造函數中的第一個語句
2. this關鍵字在構造函數中不能出現相互調用的情況,因爲是一個死循環。


例:


  1. class Student{


  2. int id;  //×××


  3. String name;  //名字


  4. //目前情況:存在同名 的成員 變量與局部變量,在方法內部默認是使用局部變量的。

  5. public Student(int id,String name){  //一個函數的形式參數也是屬於局部變量。

  6. this(name); //調用了本類的一個參數的構造方法

  7. //this(); //調用了本類無參的 構造方法。

  8. this.id = id; // this.id = id 局部變量的id給成員變量的id賦值

  9. System.out.println("兩個參數的構造方法被調用了...");

  10. }



  11. public Student(){

  12. System.out.println("無參的構造方法被調用了...");

  13. }


  14. public Student(String name){

  15. this.name = name;

  16. System.out.println("一個參數的構造方法被調用了...");

  17. }


  18. }



  19. class Demo{

  20. public static void main(String[] args) {

  21. Student s = new Student(110,"鐵蛋");

  22. System.out.println("編號:"+ s.id +" 名字:" + s.name);

  23. /*


  24. Student s2 = new Student("張三");

  25. System.out.println("名字:" + s2.name);

  26. */

  27. }

  28. }


this關鍵字要注意事項

1. 存在同名的成員變量與局部變量時,在方法的內部訪問的是局部變量(java 採取的是“就近原則”的機制訪問的。)
2. 如果在一個方法中訪問了一個變量,該變量只存在成員變量的情況下,那麼java編譯器會在該變量的前面添加this關鍵字。


總結

實際工作中,存在着構造函數之間的相互調用,但是構造函數不是普通的成員函數,不能通過函數名自己接調用

所以sun公司提供this關鍵字。

this是什麼

       1:在構造函數中打印this

       2:創建對象,打印對象名p

       3:this和p是一樣的都是內存地址值。

       4:this代表所在函數所屬對象的引用。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章