I have a class. In this class I declare a a private variable private Agent agent;. In my class I have
private Thread controller = new Thread() {
...
}
Within the above private thread I call getParameter which is a private method of the considered class. Within the getParameter I call one of the methods of the agent. As a result I get a NullPointerException. So, I conclude that agent is not visible from the getParameter.
Why is that? Can it be that the reason of that is that the getParameter is within the private Thread? And, if it is the case, how the described problem can be resolved?
ADDED
I realized that I need to be more specific. My code is organized like that:
public class GameWindow {
...
private Agent agent;
...
private Thread controller = new Thread() {
public void run() {
...
Agent agent = new Agent();
...
parameter = getParameter();
}
}
...
private String getParameter() {
...
agent.someMethod();
...
}
}
ADDED 2
In the GameWindow I have:
public void startWindow() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
controller.start();
}
});
}
The
NullPointerExceptionhas nothing to do with visibility. You are probably calling thegetParametermethod of a null object. Youragentvariable is declared, but not initialiazed. You may want to code something like:UPDATE AFTER CODE WAS ADDED
Your code has two definitions of
agent. The first one in the class:And the second one inside your
run()method:Your
getParameter()method does not know theagentdefined inside therun()method. It only knows theagentmember of the class, which was not initialized. Your problem will be solved when you remove the second definition ofagent:OLD UPDATE:
The
NullPointerExceptionis thrown inside thegetParameter()method. So I understand your code is like the following:If this is your code, the problem remains the same:
agentis not initialized. You must initialize it before calling any of its methods inside thegetParameter()method.