- Java面向對象軟件開發
- 姚駿屏 汪衛星主編
- 488字
- 2018-12-29 19:04:15
2.1.5 this關鍵字
因為有時方法需要調用該方法本身所屬對象,為此Java定義了this關鍵字。在程序中,可以在任何方法內使用this來引用當前的對象,this就指向了這個對象本身。
歸納起來,this的使用場合有以下幾種:
(1)訪問當前對象的數據成員。其使用形式如下:
this.數據成員
下面的示例就是借助this來訪問Rectangle類的實例變量width和length:
// 調用當前對象的成員變量 System.out.println("長:"+this.length+"\t寬:"+this.width);
(2)訪問當前對象的成員方法。其使用形式如下:
this.成員方法
// 調用當前對象的成員方法
System.out.println("長方形的面積是:"+this.area());
【例2-3】 在【例2-2】的基礎上修改Rectangle類的構造方法,使其形式參數與成員變量名稱相同,實現同樣功能。
因為this可以直接引用這個對象,那么this.就表示要使用這個對象中的成員,這樣就解決了實例變量和局部變量可能出現的名字空間沖突問題。
public class Rectangle{ double length; // 長 double width; // 寬 // 帶參構造方法,用于初始化長方形的長和寬 Rectangle(double width, double length){ this.width=width; //this關鍵字表示當前對象 this.length = length; } // 求長方形的面積 double area(){ return this.length*this.width; } // 打印輸出 void display(){ // 調用當前對象的成員變量 System.out.println("長:"+this.length+"\t寬:"+this.width); // 調用當前對象的成員方法 System.out.println("長方形的面積是:"+this.area()); } } public class RectangleDemo{ public static void main (String args[]){ // 調用帶參構造方法 Rectangle rect1 = new Rectangle(10,20); rect1.display(); // 調用對象rect1的成員方法 } }
該程序的運行結果如下:
長:20.0 寬:10.0 長方形的面積是:200.0
推薦閱讀
- Ceph Cookbook
- PyTorch Artificial Intelligence Fundamentals
- MySQL 8 DBA基礎教程
- Getting Started with SQL Server 2012 Cube Development
- WordPress Plugin Development Cookbook(Second Edition)
- Eclipse Plug-in Development:Beginner's Guide(Second Edition)
- Java項目實戰精編
- Apache Mahout Clustering Designs
- INSTANT Passbook App Development for iOS How-to
- WordPress 4.0 Site Blueprints(Second Edition)
- 玩轉.NET Micro Framework移植:基于STM32F10x處理器
- Python機器學習與量化投資
- Clojure Data Structures and Algorithms Cookbook
- HTML5 and CSS3:Building Responsive Websites
- jBPM6 Developer Guide