• Post Reply Bookmark Topic Watch Topic
  • New Topic

Instance Variable & Class Variable  RSS feed

 
Jaime Caetano
Ranch Hand
Posts: 32
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Barry Burd
Author
Ranch Hand
Posts: 133
10
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not everyone uses the terminology the same way. In many cases, "class variable" means "static variable". Do you have evidence to the contrary?
 
Jaime Caetano
Ranch Hand
Posts: 32
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure... That is how my teacher refers to it. class and instance variables.


Is an instance variable related to an object?
 
Barry Burd
Author
Ranch Hand
Posts: 133
10
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jaime Caetano
Ranch Hand
Posts: 32
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jaime Caetano
Ranch Hand
Posts: 32
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is amazing! I got it, Thanks to both ;D
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!