I’m trying to work this out.
In my project, i have a file called ‘Hello.java’ which is the file with the main() argument and which is called when the program is compiled. And I have another file called MyObj.java which has got just a random class I made up to test java’s OO features. I’m trying to do this:
class Hello { public MyObj an_obj; public static void main(String[] args) { setObj(); } public void setObj() { this.an_obj.set_size(7); say('size is ' + this.an_obj.get_size()); } }
In the MyObj.java class i have this code:
public class MyObj { private int size; public MyObj() { //do nothing } public void set_size(int new_size) { this.size=new_size; } public int get_size() { return this.size; } }
This however gives the error:
‘Cannot make a static reference to non-static method setObj() from the type Hello’.
If I add ‘static’ to the declaration of setObj, i.e
public static void setObj()
Then I get:
Cannot make a static reference to non-static field an_obj.
My question is, how can I accomplish what I’m doing, i.e setting and retreiving an object’s field if the only way to start a program is with the Main method, and the main Method can only call static methods?? In what, how can I do anything at all with this limitation of being able to call static methods only?????
You can either add ‘static’ to the member variable as well, or instantiate the class from within your main method. Here is some example code for both approaches:
The primary difference between these two approaches is that in the first, ‘an_obj’ is static–that is to say, there is only one variable for the entire program. If you were to instantiate multiple Hello objects, they would all have the same ‘an obj’ reference. In the second, each Hello object has its own ‘an obj’ reference, each of which can point to a different MyObj instance.
Obviously in this simple situation it doesn’t make any difference one way or the other, but generally speaking, static members and methods should be avoided when possible.