我何时在Java中使用类变量与实例变量?

Aar*_*ron 0 java oop instance-variables class-variables

这是我定义的泛型类,我想知道的是当我使用类变量创建更具体的类(例如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);
}
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

我个人对类变量的理解是,在类中声明的类变量的单个副本将使用关键字static声明,并且已从类中实例化的每个对象将包含该类的单个副本变量.

不,不是"每个对象都包含一个副本".静态变量与类型相关联,而不是与类型的每个实例相关联.的情况下不具备可变的.

只有一个变量(假设您只是从一个类加载器加载它),但是有很多类型的实例.没有实例?还有一个变量.一百万个实例?还有一个变量.

静态变量主要用于常量或常数 - 例如记录器或"有效价格集"等.在应用程序过程中不会发生变化的事情.它们应该几乎总是final在我的经验中,并且类型应该是不可变类型(如String).在可能的情况下,也为静态变量使用不可变集合 - 或者确保变量是私有的,并且永远不要在类中改变集合.

您应该避免使用静态变量来存储全局更改状态.它使代码更难以测试和推理.