Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
988 views
in Technique[技术] by (71.8m points)

oop - Object Variables vs Class Variables in 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Here's an example:

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++;
    }
}

usage:

Foobar obj1 = new Foobar();
Foobar obj2 = new Foobar();
System.out.println("obj1 id : " + obj1.id + " obj2.id "+ obj2.id + " id count " + Foobar.counter);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...