I have a Java class in which every method was defined as static
. So that I don't ha开发者_如何学JAVAve 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;
}
class methods share the same memory location for all instances of the object
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.
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?
Yes and yes. This is why having non-final static fields is generally considered a bad thing.
Keep a static private instance
class Foo {
private static Foo myInstance = new Foo();
public static void MyPretendInstanceMethod() {
myInstance.doBar();
}
private void doBar() {
// do stuff here
}
}
Add synchronization as necessary.
Static methods can only access static class variables. They cannot access instance variables because static methods are not tied to any specific instance of the class.
You don't need to create a new instance of a class in order to access a static member or variable (as long as it's public). In your example, you can call methodB like this:
String bString = MyClass.methodB();
As you can see, no new instance had to be created.
But because methodA is not static, you must create an instance of the class in order to call it, like you did in your example:
MyClass myClass = new MyClass();
String aString = myClass.methodA();
精彩评论