Java基础02 方法与数据成员
作者:Vamei 出處:http://www.cnblogs.com/vamei 歡迎轉載,也請保留這段聲明。謝謝!
?
在Java基礎01 從HelloWorld到面向對象,我們初步了解了對象(object)。對象中的數據成員表示對象的狀態。對象可以執行方法,表示特定的動作。
此外,我們還了解了類(class)。同一類的對象屬于相同的類型(type)。我們可以定義類,并使用該定義來產生對象。
我們進一步深入到對象。了解Java中方法與數據成員的一些細節。
?
調用同一對象的數據成員
方法可以調用該對象的數據成員。比如下面我們給Human類增加一個getHeight()的方法。該方法返回height數據成員的值:
public class Test {public static void main(String[] args){Human aPerson = new Human();System.out.println(aPerson.getHeight());}}class Human {/*** accessor*/int getHeight(){return this.height;}int height; }我們新增了getHeight方法。這個方法有一個int類型的返回值。Java中使用return來返回值。
?
注意this,它用來指代對象自身。當我們創建一個aPerson實例時,this就代表了aPerson這個對象。this.height指aPerson的height。
this是隱性參數(implicit argument)。方法調用的時候,盡管方法的參數列表并沒有this,Java都會“默默”的將this參數傳遞給方法。
(有一些特殊的方法不會隱性傳遞this,我們會在以后見到)
?
this并不是必需的,上述方法可以寫成:
/*** accessor*/int getHeight(){return height;}Java會自己去判斷height是類中的數據成員。但使用this會更加清晰。
我們還看到了/** comments? */的添加注釋的方法。
?
方法的參數列表
Java中的方法定義與C語言中的函數類似。Java的方法也可以接收參數列表(argument list),放在方法名后面的括號中。下面我們定義一個growHeight()的方法,該方法的功能是讓人的height增高:
public class Test {public static void main(String[] args){Human aPerson = new Human();System.out.println(aPerson.getHeight());aPerson.growHeight(10);
System.out.println(aPerson.getHeight());}}class Human { /*** accessor*/int getHeight(){return this.height;}
/**
* pass argument
*/
void growHeight(int h){this.height = this.height + h;}
int height; }
在growHeight()中,h為傳遞的參數。在類定義中,說明了參數的類型(int)。在具體的方法內部,我們可以使用該參數。該參數只在該方法范圍,即growHeight()內有效。
在調用的時候,我們將10傳遞給growHeight()。aPerson的高度增加了10。
?
調用同一對象的其他方法
在方法內部,可以調用同一對象的其他方法。在調用的時候,使用this.method()的形式。我們還記得,this指代的是該對象。所以this.method()指代了該對象自身的method()方法。
?
比如下面的repeatBreath()函數:
public class Test {public static void main(String[] args){Human aPerson = new Human();aPerson.repeatBreath(10);}}class Human {void breath(){System.out.println("hu...hu...");}/*** call breath()*/void repeatBreath(int rep){int i;for(i = 0; i < rep; i++) {this.breath();}}int height; }為了便于循環,在repeatBreath()方法中,我們聲明了一個int類型的對象i。i的作用域限定在repeatBreath()方法范圍內部。
(這與C語言函數中的自動變量類似)
?
數據成員初始化
在Java中,數據成員有多種初始化(initialize)的方式。比如上面的getHeight()的例子中,盡管我們從來沒有提供height的值,但Java為我們挑選了一個默認初始值0。
基本類型的數據成員的默認初始值:
- 數值型: 0
- 布爾值: false
- 其他類型: null
?
我們可以在聲明數據成員同時,提供數據成員的初始值。這叫做顯式初始化(explicit initialization)。顯示初始化的數值要硬性的寫在程序中:
public class Test {public static void main(String[] args){Human aPerson = new Human();System.out.println(aPerson.getHeight());}}class Human {/*** accessor*/int getHeight(){return this.height;}int height = 175; }這里,數據成員height的初始值為175,而不是默認的0了。
Java中還有其它初始化對象的方式,我將在以后介紹。
?
總結
return
this, this.field, this.method()
默認初始值,顯式初始化
?
歡迎繼續閱讀“Java快速教程”系列文章
?
總結
以上是生活随笔為你收集整理的Java基础02 方法与数据成员的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有线网卡和无线网卡同时上网 优先级切换的
- 下一篇: 【腾讯第二届校园编程马拉松】HDU-45