Thanks for your reply. Say if i have a setter method like as follows:
Is the above assign correct way? If so, i am getting a warning saying that,
Field instance should be accessed in a static way
Its correct waring because, as its static variable is should be accessed using Classname. So if i change it with class name like , am i referring to current class instance or new one? I am confused here. Please suggest me.
First of all, if you are trying to implement the singleton design pattern, you would not want a public static setInstance method in the class. The idea of the MySingletonClass I gave you is that the class itself controls the creation of instances.
About the warning message the compiler gives you ("Field instance should be accessed in a static way"): Yes, you get the warning because you are accessing a static variable via an instance (the "this" reference), instead of the class name. It's allowed to access static members via an instance in Java, but it's bad style and confusing - because you're changing the value of the static variable for all instances, not just for the one you're using to access the variable.
If you change the line of code to "MySingletonClass.instance = instance", you will not get the warning anymore.
MySingletonClass.instance refers to exactly the same variable as this.instance - there is only one member variable called "instance" for the class.
You see now why it's confusing to refer to a static variable via an object reference (the "this" reference in your case) - you easily get confused.
Joined: Dec 20, 2005
Thank you. Your explanation is really very good. Now i have understood about private static and when & how it has to be used.
Originally posted by Jesper de Jong: It's allowed to access static members via an instance in Java, but it's bad style and confusing - because you're changing the value of the static variable for all instances, not just for the one you're using to access the variable.
Not only that - for an instance variable that is hidden by an instance variable of the same name in a subclass, which of them is used in the code is actually not determined based on the runtime type of the object, but on the compile time type of the reference.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Dec 20, 2005
Sorry i didnt understand your post. Could you please be more clear if possible with a small code snippet.