这是我定义的一个泛型类,我想知道的是,当我创建更具体的类时,例如 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);
}
}