1、調用同一對象的數據成員
方法可以調用該對象的數據成員。比如下面我們給Human類增加一個getHeight()的方法。該方法返回height數據成員的值:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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并不是必需的,上述方法可以寫成:
1
2
3
4
5
6
7
|
/** * accessor */ int getHeight() { return height; } |
Java會自己去判斷height是類中的數據成員。但使用this會更加清晰。
我們還看到了/** comments */的添加注釋的方法。
2、方法的參數列表
Java中的方法定義與C語言中的函數類似。Java的方法也可以接收參數列表(argument list),放在方法名后面的括號中。下面我們定義一個growHeight()的方法,該方法的功能是讓人的height增高:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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。
3、調用同一對象的其他方法
在方法內部,可以調用同一對象的其他方法。在調用的時候,使用this.method()的形式。我們還記得,this指代的是該對象。所以this.method()指代了該對象自身的method()方法。
比如下面的repeatBreath()函數:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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語言函數中的自動變量類似)
4、數據成員初始化
在Java中,數據成員有多種初始化(initialize
)的方式。比如上面的getHeight()的例子中,盡管我們從來沒有提供height的值,但Java為我們挑選了一個默認
初始值0。
基本類型的數據成員的默認初始值:
數值型: 0
布爾值: false
其他類型: null
我們可以在聲明數據成員同時,提供數據成員的初始值。這叫做顯式初始化(explicit initialization)。顯示初始化的數值要硬性的寫在程序中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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中還有其它初始化對象的方式,我將在以后介紹。
5、總結
return
this, this.field, this.method()
默認初始值,顯式初始化
到此這篇關于Java基礎 方法與數據成員的文章就介紹到這了,更多相關Java 方法與數據成員內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/vamei/archive/2013/03/25/2964430.html