Java基础教程之对象的方法与数据成员(2)
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。
基本类型的数据成员的默认初始值:
1.数值型: 0
2.布尔值: false
3.其他类型: 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()
默认初始值,显式初始化