Java中的对象变量与类变量 [英] Object Variables vs Class Variables in Java
本文介绍了Java中的对象变量与类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习Java,我不理解对象变量和类变量之间的区别。我所知道的是,为了使它成为一个类变量,你必须先用静态语句声明它。
谢谢!
I am in the process of learning Java and I don't understand the difference between Object Variables and Class Variable. All I know is that in order for it to be a Class Variable you must declare it first with the static statement. Thanks!
推荐答案
在Java(以及一般的OOP)中,对象有两种字段(变量) 。
In Java (and in OOP in general) the objects have two kinds of fields(variable).
实例变量(或对象变量)是属于对象特定实例的字段。
Instance variables(or object variable) are fields that belong to a particular instance of an object.
静态变量(或类变量)对同一个类的所有实例都是通用的。
Static variables (or class variable) are common to all the instances of the same class.
这是一个例子:
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++;
}
}
用法:
Foobar obj1 = new Foobar();
Foobar obj2 = new Foobar();
System.out.println("obj1 id : " + obj1.id + " obj2.id "+ obj2.id + " id count " + Foobar.counter);
这篇关于Java中的对象变量与类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文