Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 245
foobar5512 Avatar asked Dec 24 '11 01:12

foobar5512


People also ask

What is the difference between class variables and instance variables in Java?

Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.

What is the difference between object and object variable in Java?

Simple variable can only hold one value (string, number, boolean etc). Object can hold pairs of variables and values, also that object model can be used for another object just different values, and oop is based on that, using same code multiple times with diff value s without rewriting it.


2 Answers

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);
like image 32
Heisenbug Avatar answered Sep 23 '22 11:09

Heisenbug


An object variable or instance member belongs to a specific instance of a class. That is to say that every instance has its own copy of that piece of data. A class variable or static member is shared by every instance of the class. That is to say that there is only one copy of that piece of data no matter how many class instances there are.

like image 89
bobbymcr Avatar answered Sep 21 '22 11:09

bobbymcr