this怎麽用(基礎)
this關鍵字代表是對象的引用。也就是this在指向一個對象,所指向的對象就是調用該函數的對象引用。
this關鍵字作用
1. 如果存在同名成員變量與局部變量時,在方法內部默認是訪問局部變量的數據,可以通過this關鍵字指定訪問成員變量的數據。
2. 在一個構造函數中可以調用另外一個構造函數初始化對象。
例: 使用java類描述一個動物。
問題:存在同名的成員變量與局部變量時,在方法的內部訪問的是局部變量(java 采取的是就近原則的機制訪問的。)
class Animal{
String name ; //成員變量
String color;
public Animal(String n , String c){
name = n;
color = c;
}
//this關鍵字代表了所屬函數的調用者對象
public void eat(){
//System.out.println("this:"+ this);
String name = "老鼠"; //局部變量
System.out.println(name+"在吃..."); //需求: 就要目前的name是成員變量的name.
}
}
class Demo6
{
public static void main(String[] args)
{
Animal dog = new Animal("狗","白色"); //現在在內存中存在兩份name數據。
Animal cat = new Animal("貓","黑色");
cat.eat();
}
}
this關鍵字調用其他的構造函數要註意的事項
1. this關鍵字調用其他的構造函數時,this關鍵字必須要位於構造函數中的第一個語句。
2. this關鍵字在構造函數中不能出現相互調用的情況,因為是一個死循環。
例:
class Student{
int id; //×××
String name; //名字
//目前情況:存在同名 的成員 變量與局部變量,在方法內部默認是使用局部變量的。
public Student(int id,String name){ //一個函數的形式參數也是屬於局部變量。
this(name); //調用了本類的一個參數的構造方法
//this(); //調用了本類無參的 構造方法。
this.id = id; // this.id = id 局部變量的id給成員變量的id賦值
System.out.println("兩個參數的構造方法被調用了...");
}
public Student(){
System.out.println("無參的構造方法被調用了...");
}
public Student(String name){
this.name = name;
System.out.println("一個參數的構造方法被調用了...");
}
}
class Demo{
public static void main(String[] args) {
Student s = new Student(110,"鐵蛋");
System.out.println("編號:"+ s.id +" 名字:" + s.name);
/*
Student s2 = new Student("張三");
System.out.println("名字:" + s2.name);
*/
}
}
this關鍵字要註意事項
1. 存在同名的成員變量與局部變量時,在方法的內部訪問的是局部變量(java 采取的是“就近原則”的機制訪問的。)
2. 如果在一個方法中訪問了一個變量,該變量只存在成員變量的情況下,那麽java編譯器會在該變量的前面添加this關鍵字。
總結
實際工作中,存在著構造函數之間的相互調用,但是構造函數不是普通的成員函數,不能通過函數名自己接調用
所以sun公司提供this關鍵字。
this是什麽
1:在構造函數中打印this
2:創建對象,打印對象名p
3:this和p是一樣的都是內存地址值。
4:this代表所在函數所屬對象的引用。
this怎麽用(基礎)