【发布时间】:2012-07-23 01:38:54
【问题描述】:
这是我定义的一个泛型类,我想知道的是,当我创建更具体的类(例如 CAR 类)时,我何时使用类变量?我个人对类变量的理解是,已经在类中声明的类变量的单个副本将使用关键字static进行声明,并且从该类中实例化的每个对象都将包含该类的单个副本变量。
实例变量允许从该类创建的类/对象的每个实例对每个对象都有一个单独的实例变量副本?
所以实例变量对于定义类/数据类型的属性很有用,例如 House 会有一个位置,但现在我什么时候在 House 对象中使用类变量?或者换句话说,在设计类时,类对象的正确用途是什么?
public class InstanceVaribale {
public int id; //Instance Variable: each object of this class will have a seperate copy of this variable that will exist during the life cycle of the object.
static int count = 0; //Class Variable: each object of this class will contain a single copy of this variable which has the same value unless mutated during the lifecycle of the objects.
InstanceVaribale() {
count++;
}
public static void main(String[] args) {
InstanceVaribale A = new InstanceVaribale();
System.out.println(A.count);
InstanceVaribale B = new InstanceVaribale();
System.out.println(B.count);
System.out.println(A.id);
System.out.println(A.count);
System.out.println(B.id);
System.out.println(B.count);
InstanceVaribale C = new InstanceVaribale();
System.out.println(C.count);
}
}
【问题讨论】:
-
尽可能避免使用它们。没有静态变量的程序更容易维护,它们基本上是带有糖衣的全局变量
-
它们实际上被称为“静态字段”,而不是“类变量”。
标签: java oop instance-variables class-variables