Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Variable Issues  RSS feed

 
Samarth Kumar
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
folks,
i am trying to learn the subtle differences between the different sort of variables in java. the first two that i have tackled are,
class variables and instance variables. from what i have understood, please go through the code that i wrote and tell me if my understanding of this code is correct or not.
public class Example
{
String s = "This is a string" ;
}
the attribute "s" defined above in the Example class is a class variable. all instances of Example will have a String attribute "s" whose value would be "This is a string".
is it advisable to put a static qualifier on s? if yes why so?
public class Test
{
public static void main( String args[] )
{
Example exampleInstance = new Example() ;
System.out.println( exampleInstance.s ) ;
}
}
in the above code, exampleInstance is an instance of the class Example. therefore exampleInstance is an instance variable of type Example which has a class variable s.
is my understanding on this correct?
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your first example, the variable "s" is an instance variable, not a class variable. To make it a class variable you need to use the "static" qualifier.
However as the class designer YOU have to make that decision. If you want the instances of the class to be able to change the value of "s" without affecting other instances, then it needs to be left alone. If you really want every instances of the class to share the same "s", then make it static. In that case there will be only one "s" regardless of how many instances are created.
In your second example you are correct in that "exampleInstance" is an instance of class "Example". But as explained above, "s" won't be static unless you explicitly declare it to be.
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at this sample class:

If you run it, the results will be:

Since "str1" is static (class variable), changing it using ex1.str1 = "new foo"; affected all instances. However "str2" isn't static, so changing it using ex2.str2 = "new bar"; affected only "ex2" instance.
Play around with it for a while and you'll get the drift.
[ March 30, 2004: Message edited by: Wayne L Johnson ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!