Forums Register Login
Instance Variable & Class Variable
I'm having trouble to fully understand the difference between instance and class variables.

I though it was all about the static, i.e:

int age; // instance variable

static int age; // class variable

Can anyone tell me what's behind this?

Thanks, Jaime.
Not everyone uses the terminology the same way. In many cases, "class variable" means "static variable". Do you have evidence to the contrary?
I'm not sure... That is how my teacher refers to it. class and instance variables.

Is an instance variable related to an object?
Let's say you have a class and three objects:

and inside another class:

Then you have three different oneValue's:

and you have only one anotherValue:

I'm not sure that this is what you were asking. Is it? A class value is (in my use of the term) another way of saying "static variable" but your instructor might be using the term differently.
so when you access the static/class variable there's no need of creating an object cause it's value would be the same anywhere right?
(1 like)
An instance variable is a non-static member variable; each object of the class will have its own copy of the variable.

A class variable is a static member variable; there is only one copy of it, which is shared by all objects of the class. You don't need to have an instance (= an object) of the class to access it; normally you would access it using the class name: ClassName.variable

See Understanding Class Members in Oracle's Java Tutorials.
this is amazing! I got it, Thanks to both ;D

This thread has been viewed 502 times.

All times above are in ranch (not your local) time.
The current ranch time is
Dec 11, 2018 22:08:52.