I would like to understand this once and for all.
With this please excuse the mass of code pasted below, but I do not want to leave out any details.
The only
It's a good idea in this case to make the method static. The other way is to use
new GarageComm().readPositions("holdingsBU.txt")
instead.
So, why this error?
A static method can not call a non-static method in the same class. It sounds bizarre, but there is a reason for it. Consider this:
Non static methods may depend on the state of the objects, the instance variable to say.
Static methods can be called from out-side without instanciating
Now, if we allow static methods to play with non-static method (and non static variables), they might fail. So, it is a kind of prevention.
When should I consider making a method static?
Now, come to, why not make the method static
?,
Very well, you should make a method static if it's functionality does not depend on the object's state.
If it just uses the passed parameters and some static stuffs (static variable, static methods) and returns (with/without a result, throwing exception anything), consider making it static method.
update: looked like this post confused a couple of people so updated the answer.
You need to make your function static:
public static HashMap readPositions(String destFile) {
...
}
Creating an instance of GarageComm would work too, but this is bad programming practice in Java, since that object has no state.
This is a typical mindbender for new Java programmers.
A static
method does not belong to an object. A non-static
method belongs to an object.
You use the main
-method convention to have your program started, and it is required that that method must be static.
The trick to get from a static
method to a non-static
method, is that you must create an object so you can call the method on that. I.e. new GarageComm().readPositions(...)
. I just don't think you have to here, so it would be simpler to just mark readPositions as static too.
If a method is not static, then it must be called "on" an object. When calling a method from a non-static method, that object is implied -- it's the object the first method was called on. But when calling it from a static method, there is no implied object, so to call the method, you must supply an object:
GarageComm gc = new GarageComm();
hashPos= gc.readPositions("holdingsBU.txt");
Since GarageComm
has no state of its own, there's no reason to create a GarageComm
object, so it's just as well you mark the method static, so no object is required to call it.
Real solution? Don't put so much stuff in the main()
method. That's for noobs.
Java's an object-oriented language. Put the logic inside methods associated with the GarageComm
class. main()
should do little more than instantiate an instance and call its methods.
Change it like this:
GarageComm gc = new GarageComm();
hashPos= gc.readPositions("holdingsBU.txt");//the error is here