Java中的对象变量与类变量

foo*_*512 12 java oop variables static object

我正在学习Java,我不理解对象变量和类变量之间的区别.我所知道的是,为了使它成为一个类变量,你必须先用静态语句声明它.谢谢!

Hei*_*bug 15

在Java(以及一般的OOP)中,对象有两种字段(变量).

实例变量(或对象变量)是属于对象的特定实例的字段.

静态变量(或类变量)对于同一个类的所有实例都是通用的.

这是一个例子:

public class Foobar{
    static int counter = 0 ; //static variable..all instances of Foobar will share the same counter and will change if such is done
    public int id; //instance variable. Each instance has its own id
    public Foobar(){
        this.id = counter++;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

Foobar obj1 = new Foobar();
Foobar obj2 = new Foobar();
System.out.println("obj1 id : " + obj1.id + " obj2.id "+ obj2.id + " id count " + Foobar.counter);
Run Code Online (Sandbox Code Playgroud)


der*_*ann 2

对象变量的状态依赖于类的特定实例,而类变量可以通过类本身进行全局访问。这可能有点模糊,所以这里有一些例子:

class Muffin {

    private static final int calories = 9320;

    public String flavor;

    public Muffin( String flavor ){
        this.flavor = flavor;
    }

}
Run Code Online (Sandbox Code Playgroud)

在这个类中,calories是一个类变量。在任何其他代码段中,您可以通过调用 来获取任何类型的松饼中的卡路里数Muffin.calories。在这种情况下,final关键字也用于使卡路里数保持不变。

在同一个类中,我们有一个对象变量flavor。这取决于类的实例,并在构造函数中设置。

Muffin myMuffin = new Muffin( "blueberry" );
Run Code Online (Sandbox Code Playgroud)

所以现在您可以通过调用 来访问这种特定松饼的味道myMuffin.flavor。请注意,我们需要如何实例化一个Muffin对象,然后才能访问它的flavor.

更改静态(类)变量

上面的例子有点夸张,因为不同类型的松饼有不同的卡路里含量。它们对于常量很有用,但这里是静态变量的值发生变化的情况:

class Muffin {

    private static int next_id = 1;

    public int id;
    public String flavor;

    public Muffin( String flavor ){
        this.flavor = flavor;
        id = next_id++;
    }

}
Run Code Online (Sandbox Code Playgroud)

在第二个示例中,我们需要为创建的每个松饼有一个唯一的 ID 号,因此我们可以有一个静态变量,每次Muffin实例化 a 时该变量都会递增。该static关键字使 的值next_id在每次调用构造函数时都保持不变,因此id对于每个新松饼, 都会有所不同并继续增加。