Java基础教程之类数据与类方法
我们一直是为了产生对象而定义类(class)的。对象是具有功能的实体,而类是对象的类型分类。这是面向对象的一个基本概念。
在继承(inheritance)中,我们将类当做可以拓展的主体,这提高了我们对“类”的认识。
类本身还有许多值得讨论的地方。我们将继续深入
static数据成员
有一些数据用于表述类的状态。比如Human类,我们可以用“人口”来表示Human类的对象的总数。“人口”直接描述类的状态,而不是某个对象。
Human类的人口为8
类的所有对象共享“人口”数据。这样的数据被称为类数据成员(class field)。
在类定义中,我们利用static关键字,来声明类数据成员,比如:
class Human
{
/**
* constructor
*/
public Human(int h)
{
this.height = h;
}
/**
* accessor
*/
public int getHeight()
{
return this.height;
}
/**
* mutator
*/
public void growHeight(int h)
{
this.height = this.height + h;
}
/**
* breath
*/
public void breath()
{
System.out.println("hu...hu...");
}
private int height;
private static int population;
public static boolean is_mammal = true;
}
我们定义了两个类数据成员: population和is_mammal。所有Human对象都共享一个population数据;任意Human对象的is_mammal(是哺乳动物)的属性都为true。
类数据成员同样要设置访问权限。对于声明为public的类数据成员,可以利用class.field的方式或者object.field(如果存在该类的对象)的方式从外部直接访问。这两种访问方式都是合理的,因为类数据成员可以被认为是类的属性,可以认为是所有成员共享的属性。如果类数据成员被定义为private,那么该类数据成员只能从类的内部访问。
(上面将is_mammal设置成了public,只是为了演示。这样做是挺危险的,万一有人使用 Human.is_mammal=false;,所有人类都遭殃。还是那个基本原则,要尽量将数据设置为private。)
static方法
我们也可以有类方法,也就是声明为static的方法。类方法代表了类可以实现的动作,其中的操作不涉及某个具体对象。如果一个方法声明为static,那么它只能调用static的数据和方法,而不能调用非static的数据和方法。
事实上,在static方法中,将没有隐式传递的this和super参数。我们无从引用属于对象的数据和方法(这正是我们想要的效果)。
综合上面所说的,我们有如下关系:
红色的虚线表示不能访问。也就是说,类方法中,不能访问对象的数据。
下面我们增加一个static方法getPopulation(),该方法返回static数据population:
class Human
{
/**
* constructor
*/
public Human(int h)
{
this.height = h;
}
/**
* accessor
*/
public int getHeight()
{
return this.height;
}
/**
* mutator
*/
public void growHeight(int h)
{
this.height = this.height + h;
}
- 上一篇:J2SE与c#的几点比较
- 下一篇:Java基础教程之继承详解