调用同一对象的数据成员
方法可以调用该对象的数据成员。比如下面我们给 Human
类增加一个 getHeight()
的方法。该方法返回 height
数据成员的值:
class Human
{
int getHeight()
{
return this.height;
}
int height;
}
public class Test
{
public static void main(String[] args)
{
Human aPerson = new Human(); // 创建一个 Human 对象
System.out.println(aPerson.getHeight());
}
}
输出结果:
0
我们新增了 getHeight()
方法。这个方法有一个 int
类型的返回值。Java 中使用 return
来返回值。
注意 this
,它用来指代对象自身。当我们创建一个 aPerson
实例时,this
就代表了 aPerson
这个对象。this.height
指 aPerson
的height
。
this
是隐性参数(implicit argument)。方法调用的时候,尽管方法的参数列表并没有 this
,Java 都会默默的将 this
参数传递给方法。
方法的参数列表
Java 的方法可以接收 参数列表(argument list),放在方法名后面的括号中。下面我们定义一个 growHeight()
的方法,该方法的功能是让人的 height
增高:
class Human
{
int getHeight()
{
return this.height;
}
void growHeight(int h)
{
this.height = this.height + h;
}
int 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());
}
}
输出结果:
0
10
在 growHeight()
方法中,h
为传递的参数。在类定义中,说明了参数的类型为 int
。在具体的方法内部,我们可以使用该参数。该参数只在该方法范围,即 growHeight()
内有效。
在调用的时候,我们将 10 传递给 growHeight()
。aPerson
的高度增加了10。
调用同一对象的其他方法
在方法内部,可以调用同一对象的其他方法。在调用的时候,使用 this.method()
的形式。我们还记得,this
指代的是该对象。所以 this.method()
指代了该对象自身的 method()
方法。
比如下例中重复呼吸的方法,repeatBreath()
:
class Human
{
void breath()
{
System.out.println("hu...hu...");
}
void repeatBreath(int rep)
{
int i;
for(i = 0; i < rep; i++) {
this.breath(); // 调用自身的 breath() 方法
}
}
}
public class Test
{
public static void main(String[] args)
{
Human aPerson = new Human();
aPerson.repeatBreath(10);
}
}
输出结果:
hu...hu...
hu...hu...
hu...hu...
hu...hu...
hu...hu...
hu...hu...
hu...hu...
hu...hu...
hu...hu...
hu...hu...
为了便于循环,在 repeatBreath()
方法中,我们声明了一个 int
类型的对象 i
。i
的作用域限定在 repeatBreath()
方法范围内部。
数据成员初始化
在 Java 中,数据成员有多种 初始化 (initialize)的方式。比如上面的 getHeight()
的例子中,尽管我们从来没有提供 height
的值,但 Java 为我们挑选了一个默认初始值 0。
基本类型的数据成员的默认初始值:
- 数值型: 0
- 布尔值::false
- 其他类型: null
我们可以在声明数据成员同时,提供数据成员的初始值。这叫做 显式初始化 (explicit initialization)。显示初始化的数值要硬性的写在程序中:
class Human
{
int getHeight()
{
return this.height;
}
int height = 175; // 显式初始化
}
public class Test
{
public static void main(String[] args)
{
Human aPerson = new Human();
System.out.println(aPerson.getHeight());
}
}
输出结果:
175
网友评论