I'm having a bit of a problem getting my head around inheriting class variables.
The situtaion is this I have a super class called MainObject which is shown below
public class MainObject
private static boolean debugMessageFlag = false;
public void debugMessage(Object anObject)
public static boolean getDebugMessageFlag()
public static void setDebugMessageFlag(boolean aBoolean)
debugMessageFlag = aBoolean;
I then sub class this object and execute the code below
this seems to set the MainObject classes class variable debugMesageFlag to true also.
What I thought would happen is that I could define the class variable and methods in MainObject and then sub class this object and that every sub class of the MainObject class would have its own class variable debugMessageFlag, but it currently seems that that every sub class refers to MainObjects debugMessageFlag variable.
Any suggestions where I'm going wrong?
Welcome to JavaRanch!
You're going wrong at square one, I'm afraid, in your expectation that inheriting a class variable means that a subclass gets its own copy. It doesn't. A subclass inherits access to the parent class's copy, nothing more -- Java will not create a second copy of a class variable no matter what*.
* (unless there are multiple copies of the parent class loaded by separate ClassLoaders, but that's an advanced topic not really relevant here. I mention it just to keep those pesky language lawyers happy.)
What I want to do is have the ability to switch some debug messages of mine on and off at will in any object that inherits from MainObject. I was hoping to be able to define this behaviour in MainObject and then just inherit it from there.
So is there another way of doing this using inheritence and a static variable in a good object orientented way or is it best if I just put a static var in each class I create with the accompaniying getter and setter class methods?
Originally posted by Layne Lund:
What about having a debugState variable in each subclass? I guess this would mean that each subclass needs setDebugState() and getDebugState() methods. I personally think this would be a more obvious solution than Ernest's, but it isn't necessarily any better.
It is more obvious, and also has the potential to be much better-performing. The only reason I proposed my version was because it was the closest you could get to the original poster's goal of doing everything in the base class. You could simply have static setDebugState() and getDebugState() methods in each class, and then all those methods would have to do would be to reference a flag -- but of course then you'd have to duplicate the code in each class.