Static and non-static(instance) members in Java


Static members are those which are at the class or type level. And there will be only one copy of it is available to the all instances of that class type.
And non Static (instance) members will have different copies for different instances.

Say suppose you have a class as
  
public class StaticDemo {

 public static String staticString;
 public String nonStaticString;
 
 public static void main(String[] args) {
  StaticDemo obj1 = new StaticDemo();
  StaticDemo obj2 = new StaticDemo();
  obj1.staticString = "first-Static-Value";
  obj1.nonStaticString = "first-non-Static-Value";
  
  obj2.staticString = "second-Static-Value";
  obj2.nonStaticString = "second-Non-Static-Value";
  
  
  System.out.println("Static Value obj1 : "+obj1.staticString);
  System.out.println("non Static Value obj1 : "+obj1.nonStaticString);
  System.out.println("Static Value obj2 : "+obj2.staticString);
  System.out.println("non Static Value obj2 : "+obj2.nonStaticString);
  
 }
 
}

So if you create 2 objects of the type StaticDemo then these two will have two different 'nonStaticString' members but one common staticString member which is a class member.

output of above programe

Static Value obj1 : second-Static-Value
non Static Value obj1 : first-non-Static-Value
Static Value obj2 : second-Static-Value
non Static Value obj2 : second-Non-Static-Value

If you observe below image, staticString is static variable will have only one copy and both obj1 and obj2 will share same variable(memory). If any object change the values then the latest value will be available in staticString memory; (in above example - obj1 and obj2- staticString has latest value as second-Static-Value)
and for nonStaticString, both object will have separate copy of non static members (nonStaticString).
(in above example - obj1 and obj2- nontStaticString has different values )

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...