Java中this的用法實例總結
一、this關鍵字
1.this的類型:哪個對象調(diào)用就是哪個對象的引用類型

二、用法總結
1.this.data; //訪問屬性
2.this.func(); //訪問方法
3.this(); //調(diào)用本類中其他構造方法
三、解釋用法
1.this.data
這種是在成員方法中使用
讓我們來看看不加this會出現(xiàn)什么樣的狀況
class MyDate{
public int year;
public int month;
public int day;
public void setDate(int year, int month,int day){
year = year;//這里沒有加this
month = month;//這里沒有加this
day = day;//這里沒有加this
}
public void PrintDate(){
System.out.println(year+"年 "+month+"月 "+day+"日 ");
}
}
public class TestDemo {
public static void main(String[] args) {
MyDate myDate = new MyDate();
myDate.setDate(2000,9,25);
myDate.PrintDate();
MyDate myDate1 = new MyDate();
myDate1.setDate(2002,7,14);
myDate1.PrintDate();
}
}我們想要達到的預期是分別輸出2000年9月25日,2002年7月14日。
而實際輸出的結果是

而當我們加上this時
class MyDate{
public int year;
public int month;
public int day;
public void setDate(int year, int month,int day){
this.year = year;
this.month = month;
this.day = day;
}
public void PrintDate(){
System.out.println(this.year+"年 "+this.month+"月 "+this.day+"日 ");
}
}
public class TestDemo {
public static void main(String[] args) {
MyDate myDate = new MyDate();
myDate.setDate(2000,9,25);
myDate.PrintDate();
MyDate myDate1 = new MyDate();
myDate1.setDate(2002,7,14);
myDate1.PrintDate();
}
}
就實現(xiàn)了賦值的功能,為了避免出現(xiàn)差錯,我們建議盡量帶上this
2.this.func()
這種是指在普通成員方法中使用this調(diào)用另一個成員方法
class Student{
public String name;
public void doClass(){
System.out.println(name+"上課");
this.doHomeWork();
}
public void doHomeWork(){
System.out.println(name+"正在寫作業(yè)");
}
}
public class TestDemo2 {
public static void main(String[] args) {
Student student = new Student();
student.name = "小明";
student.doClass();
}
}運行結果:

(3)this()
這種指在構造方法中使用this調(diào)用本類其他的構造方法
這種this的使用注意以下幾點
1.this只能在構造方法中調(diào)用其他構造方法
2.this要放在第一行
3.一個構造方法中只能調(diào)用一個構造方法


運行結果

總結
到此這篇關于Java中this用法總結的文章就介紹到這了,更多相關Java中this用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
利用Java實現(xiàn)圖片轉化為ASCII圖的示例代碼
本文將詳細講解如何利用 Java 實現(xiàn)圖片轉化為 ASCII 圖,從項目背景與意義、相關技術知識,到系統(tǒng)需求與架構設計,再到詳細實現(xiàn)思路、完整代碼和代碼解讀,最后對項目進行總結與展望,需要的朋友可以參考下2025-03-03
在springboot項目中同時接收文件和多個參數(shù)的方法總結
在開發(fā)接口中,遇到了需要同時接收文件和多個參數(shù)的情況,可以有多種方式實現(xiàn)文件和參數(shù)的同時接收,文中給大家介紹了兩種實現(xiàn)方法,感興趣的同學跟著小編一起來看看吧2023-08-08
SpringBean和Controller實現(xiàn)動態(tài)注冊與注銷過程詳細講解
這篇文章主要介紹了SpringBean和Controller實現(xiàn)動態(tài)注冊與注銷過程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2023-02-02

