简体   繁体   English

类java中的静态变量

[英]Static variable in class java

I want to ask if static variable in class will add extra memory the the initialized class. 我想问一下,类中的静态变量是否会为初始化类添加额外的内存。

Lets say I have a class like this: 可以说我有这样一个类:

public class Sample{

    public static String NAME[] = {"1", "2", "3", "4"};

    private int id;

    private String uuid;
    private String name;

    public void setUuidString() {
        UUID uuid = UUID.randomUUID();
        this.uuid = uuid.toString();
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setCustomUuid(String uuid) {
        this.uuid = uuid;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public String getUuid() {
        return uuid;
    }

    public String getName() {
        return name;
    }
}

And I create Sample class multiple times initializing it and adding to an array of Sample class does the static variable adds extra memory the the class or will it only get only one memory location when it is static? 我创建Sample类多次初始化它并添加到Sample类数组中静态变量是否为类增加了额外的内存,或者它只在静态时才获得一个内存位置?

Since static variables are initialized at the start of the programs execution, memory is set aside for the variable. 由于static变量在程序执行开始时被初始化,因此为变量留出了内存。 Since the variable is static it belongs to its class not instances of the class. 由于变量是static因此它属于类而不是类的实例。 So for every instance you create it will not use extra memory. 因此,对于您创建的每个实例,它都不会使用额外的内存。

With static variables a single instance of the variable is shared throughout all instances of the class, although you do not need a instance of the class to access the variable. 对于static变量,变量的单个实例在类的所有实例中共享,尽管您不需要类的实例来访问变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM