Java 類 體 中 的 this、super 的 正 確 用 法 |
|
|
一、基礎知識: 1、super(參數(shù)):調用基類中的某一個構造函數(shù)(應該為構造函數(shù)中的第一條語句)。 2、this(參數(shù)):調用本類中另一種形成的構造函數(shù)(應該為構造函數(shù)中的第一條語句); 3、super: 它引用當前對象的直接父類中的成員(用來訪問直接父類中被隱藏的父類中成員數(shù)據(jù)或函數(shù),基類與派生類中有相同成員定義時)。 如:super.變量名 super.成員函數(shù)據(jù)名(實參) 4、this:它代表當前對象名(在程序中易產(chǎn)生二義性之處,應使用this來指明當前對象;如果函數(shù)的形參與類中的成員數(shù)據(jù)同名,這時需用this來指明成員變量名)。 二、應用實例: class Point { private int x,y; public Point(int x,int y) { this.x=x; //this它代表當前對象名 this.y=y; } public void Draw() { } public Point() { this(0,0); //this(參數(shù))調用本類中另一種形成的構造函數(shù) } } class Circle extends Point { private int radius; public circle(int x0,int y0, int r ) { super(x0,y0); //super(參數(shù))調用基類中的某一個構造函數(shù) radius=r; } public void Draw() { super.Draw(); //super它引用當前對象的直接父類中的成員 drawCircle(); } } |
|
|