I have a Java class in which every method was defined as static. So that I don’t have to re-write the class, and then a good bit of code that depends upon it, I’m adding in some error reporting via an instance variable. However, Java doesn’t seem to be able to access instance variables from class methods. I read Sun’s description of class variables and am wary of just changing every method to an instance method in this class without a better understanding of how it would work in a web application.
According to (1), as I understand it, class methods share the same memory location for all instances of the object. So, in a web application, wouldn’t that mean every process references the same memory address for a static method? And, in turn, each process would re-define all of the instance methods?
If I were to create a class variable to keep track of errors, wouldn’t that introduce a situation where process A could trigger an error in process B? Can instance methods even access class variables?
Edit:
Let me clarify what I’m trying to accomplish with some example code.
First, my class:
public class MyClass {
public int error = 0;
public String methodA() {
// Do some stuff
if (ret == null) this.error = 1;
return ret;
}
public static boolean methodB() {
// Same thing but I can't access this.error here
}
}
Now my application:
MyClass myClass = new MyClass();
String aString = myClass.methodA();
if (myClass.error != 0) {
out.print("What did you do!?");
return;
}
So do instance methods. The code for all methods of a class exists only once. The difference is that instance methods always require an instance (and its fields) for context.
Yes and yes. This is why having non-final static fields is generally considered a bad thing.