Nabin
Nabin

Reputation: 11776

What is the difference between class variables and member variables in Java

There is not much to explain. The title is enough to explain the question. I got this on an interview today.

What are class variables and member variables in Java?

Thank you!

Upvotes: 1

Views: 325

Answers (2)

sTg
sTg

Reputation: 4424

A member variable is one per object, every object has its own copy of instance variable while a class variable is one per Class, every object of that class shares the same class variable..

A class variable also called as static variable is initialized when the JVM loads the class probably take an example static block if there is no main method in your program while this is not the case with your member variables.

Class variables should be used when you don't want to have copy for each instance while member variables should be used when you want separate copy for each instance of object.

From point of garbage collection class variables have a long life as class variables are associated with the class and not individual instance. class variables are cleaned up when the ClassLoader which hold the class unloaded. This is very rare..while in case of member variables they get cleaned up when the instance is cleaned up. Hope this helps.

Upvotes: 2

Andrew Orobator
Andrew Orobator

Reputation: 8646

As Zhuinden said they probably meant static variables instead of class variables. For member variables, an instance of the class is needed in order to access the variable. For example if I had a class Foo, and it had a member variable int bar, the only way I could access it is by doing something like

Foo foo = new Foo();
doSomething(foo.bar);

However, if I have bar was a static variable, that means that I can access it even though I don't have an instance of the object. I would access it like this:

doSomething(Foo.bar)

without having to create an instance of Foo.

See here

Upvotes: 3

Related Questions