Object Variables vs Class Variables in Java

后端 未结 5 1300
刺人心
刺人心 2020-12-16 17:39

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 Var

5条回答
  •  离开以前
    2020-12-16 17:57

    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);
    

提交回复
热议问题