java中this的用法示例(關(guān)鍵字this)
this是指向本身的隱含的指針,簡單的說,哪個對象調(diào)用this所在的方法,那么this就是哪個對象。
示例代碼: TestThis_1.java
/* 問題:什么是this
* 輸出結(jié)果:
* A@4e44ac6a
*/
public class TestThis_1 {
public static void main(String[] args) {
A aa = new A();
System.out.println(aa.f()); //aa.f(), 返回aa這個對象的引用(指針)
}
}
class A {
public A f() {
return this; //返回調(diào)用f()方法的對象的A類對象的引用
}
}
this的常見用法
1. 區(qū)分同名變量
示例代碼: TestThis_2.java
/* this的常見用法1:區(qū)分同名變量
* 輸出結(jié)果:
* this. i = 1
* i = 33
*/
public class TestThis_2 {
public static void main(String[] args) {
A aa = new A(33);
}
}
class A {
public int i = 1; //這個i是成員變量
/*注意:一般不這么寫,構(gòu)造函數(shù)主要是為了初始化,這么寫主要是為了便于理解*/
public A(int i) { //這個i是局部變量
System.out.printf("this. i = %d\n", this.i); //this.i指的是對象本身的成員變量i
System.out.printf("i = %d\n", i); //這里的i是局部變量i
}
}
2. 構(gòu)造方法間的相互調(diào)用
示例代碼: TestThis_3.java
/* this的常見用法2: 構(gòu)造方法中互相調(diào)用*/
public class TestThis_3 {
public static void main(String[] args) {
}
}
class A {
int i, j, k;
public A(int i) {
this.i = i;
}
public A(int i, int j) {
/* i = 3; error 如果不注釋掉就會報錯:用this(...)調(diào)用構(gòu)造方法的時候,只能把它放在第一句
* TestThis_3.java:20: error: call to this must be first statement in constructor
* this(i);
* ^
* 1 error
*/
this(i);
this.j = j;
}
public A(int i, int j, int k) {
this(i, j);
this.k = k;
}
}
注意事項
被static修飾的方法沒有this指針。因為被static修飾的方法是公共的,不能說屬于哪個具體的對象的。
示例代碼: TestThis_4.java
/*static方法內(nèi)部沒有this指針*/
public class TestThis_4 {
public static void main(String[] args) {
}
}
class A {
static A f() {
return this;
/* 出錯信息:TestThis_4.java:10: error: non-static variable this cannot be referenced from a static context
* return this;
* ^
* 1 error
*/
}
}
相關(guān)文章
SpringBoot+Vue實現(xiàn)數(shù)據(jù)添加功能
這篇文章主要介紹了SpringBoot+Vue實現(xiàn)數(shù)據(jù)添加功能,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03Springboot+AOP實現(xiàn)返回數(shù)據(jù)提示語國際化的示例代碼
這篇文章主要介紹了Springboot+AOP實現(xiàn)返回數(shù)據(jù)提示語國際化的示例代碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-07-07Java中BitMap(位圖)hutool版、IntMap、LongMap示例詳解
這篇文章主要給大家介紹了關(guān)于Java中BitMap(位圖)hutool版、IntMap、LongMap的相關(guān)資料,通過位運算高效存儲和檢索整數(shù),相比于傳統(tǒng)數(shù)組,它們在內(nèi)存占用和性能上都有顯著優(yōu)勢,需要的朋友可以參考下2024-12-12詳解SpringBoot中@NotNull,@NotBlank注解使用
這篇文章主要為大家詳細(xì)介紹了Spring?Boot中集成Validation與@NotNull,@NotBlank等注解的簡單使用,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-08-08利用Stream聚合函數(shù)如何對BigDecimal求和
這篇文章主要介紹了利用Stream聚合函數(shù)如何對BigDecimal求和問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05