• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static class instance Behavior ??  RSS feed

 
Hrishikesh Ghatnekar
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Please see following code

class Light {

private final static Light light_inst = new Light();

private Light() {}

public void doit() {
System.out.println("called DoIt");
}

public static void doneit() {
System.out.println("called DoneIt");
}

public static void main(String args[]) {
System.out.println("kjsdhsdh");
Light ll = Light.getInstance();
Light.doit();

}

public static Light getInstance() {
return light_inst;
}

}



In above code even if I am creating static instance of Light , and then using it ,

It is working as if , it is a non static instance.

And what I understood from books is that ,
static code can access only static variables/ metnods.

So dose this mean that even if I have static instance of some class and then if I assign that static instance to other normal instance , the newly created instance will behave like non static instance?


Thanks
HG
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no such thing as a "static instance" of a class. You are correct that classes can have static and non-static members (fields and methods). And static methods can only access other static methods and fields directly.

However, when you use the "new" operator, you are creating an instance of that class, and it doesn't matter where you store the reference to it. Storing the reference into a static field doesn't affect the instance you created.

To access static members of a class, you prefix them with the name of the classTo access non-static members (called instance members), you prefix them with a reference to an instance of the class. The reference can be a static field, non-static (instance) field, or local variable. The key is that they all reference an instance of the class Light -- not the class itself.The second call may be a little confusing. Since doneit() is a static method, the compiler ignores the instance that l references and looks only at the declared type of l, in this case "Light". The only time this matters is if l happens to reference a subclass of Light. If the subclass also defines a doneit() method, it will not be called since the compiler only looks at the declared type.
[ February 04, 2005: Message edited by: David Harkness ]
 
Hrishikesh Ghatnekar
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks David


Regards
HG
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!