• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between Static and Instance variable

 
NitishK Kumar
Ranch Hand
Posts: 40
Chrome Firefox Browser Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between static and instance variable?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34863
369
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A static variable is shared by all instances of the class.
 
Jacob Coddaire
Ranch Hand
Posts: 36
Chrome Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instance versus static methods
Each Java method is either an instance method or a static method. Any method not marked with the static keyword is an instance method. Lastly, all Java methods must be defined within a class. In order to call an instance method, you must first have an instance of the class within which the method you want to call is defined. Suppose we want to call an instance method named "method1" defined in class "ClassA". We could do the following:

ClassA x = new ClassA();
x.method1();

If method1 were instead static, then we would call the method by referring directly to the class itself:

ClassA.method1();

For more on the instance/static distinction, search Google for "java instance versus static method"
 
Lucky J Verma
Ranch Hand
Posts: 278
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static Variable= Defined at Class Level
Instance Variable =Defined at Instace/Object Level.

Static Variables are initialized ,loaded with Class itself.

But instance variable initialized when Object for that Class is instantiated.

In other words - For 1 class ,its different objects can have different values for same instance variable.(Each instance =can have its own value)
But for same class ,static variable (since belongs to class itself ) -same value is shared by each object.





 
NitishK Kumar
Ranch Hand
Posts: 40
Chrome Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lucky J Verma wrote:Static Variable= Defined at Class Level
Instance Variable =Defined at Instace/Object Level.

Static Variables are initialized ,loaded with Class itself.

But instance variable initialized when Object for that Class is instantiated.

In other words - For 1 class ,its different objects can have different values for same instance variable.(Each instance =can have its own value)
But for same class ,static variable (since belongs to class itself ) -same value is shared by each object.



Thank you Lucky Sir, Actually this was my doubt which I wanted to clear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic