对象中的数据成员表示对象的状态。对象可以执行方法,表示特定的动作。
调用同一对象的数据成员
public class Test{
public static void main(String[] args){
Human aPerson = new Human();
aPerson.breath();
System.out.println(aPerson.height);
}
}
class Human{
void breath(){
System.out.println("hu..hu..");
}
int height;
}
注意this,它用来指代对象自身。当我们创建一个aPerson实例时,this就代表了aPerson这个对象。this.height指aPerson的height。
this是隐性参数(implicit argument)。方法调用的时候,尽管方法的参数列表并没有this,Java都会“默默”的将this参数传递给方法。
int getHeight(){
return height;
}
Java会自己去判断height是类中的数据成员。但使用this会更加清晰。
/** comments */添加注释的方法。(可以在以后点击某个参数时,显示注释的消息)
方法的参数列表
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{
int getHeight(){
return this.height;
}
void growHeight(int h){
this.height = this.height + h;
}
int height;
}
在growHeight()中,h为传递的参数。在类定义中,说明了参数的类型(int)。在具体的方法内部,我们可以使用该参数。该参数只在该方法范围,即growHeight()内有效。在调用的时候,我们将10传递给growHeight()。aPerson的高度增加了10。
调用同一对象的其他方法
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..");
}
void repeatBreath(int rep){
int i;
for(i = 0;i < rep;i++){
this.breath();
}
}
int height;
}
数据成员初始化
在Java中,数据成员有多种初始化(initialize)的方式。比如上面的getHeight()的例子中,尽管我们从来没有提供height的值,但Java为我们挑选了一个默认初始值0。
基本类型的数据成员的默认初始值:
- 数值型: 0
- 布尔值: false
- 其他类型: null
public class Test{
public static void main(String[] args){
Human aPerson = new Human();
System.out.println(aPerson.getHeight());
}
}
class Human{
int getHeight(){
return this.height;
}
int height = 175;
}