Reputation: 5526
Im trying to apply the state pattern on a multi threaded application.The problem is that the compiler doesnt like the fact that my class extends Thread. Here is the code :
public class ConnectionHandler extends Thread
private State lockedState;
public ConnectionHandler(Socket socket){
...
lockedState = new LockedState(this);
}
public State getState(){}
public void setState(State state){}
{
public interface State {
public void PASSWD(String pass);
public void ACCESS(String file);
public void getDIR();
public void QUIT();
}
public class LockedState implements State {
ConnectionHandler connectionHandler;
public LockedState(ConnectionHandler handler){
connectionHandler=handler;
}
public void PASSWD(String pass){
public void ACCESS(String file){}
public void getDIR(){}
public void QUIT(){}
}
The error i get is on constructor of ConnectionHandler : incompatible types required java.lang.Thread.State found : Networks2.LockedState. When i remove the extends Thread from Connectionhandler it doesnt give any errors but thats not an option. So the question : What should i do so that the compiler doesnt complain ? Thanks
Upvotes: 0
Views: 683
Reputation: 24722
java.lang.Thread already contains inner class called State. So your variable is declared as different type. No wonder it fails.
Just rename your class State to MyState or whatever other name.
Also, I concur with other recommendations to use Runnable instead of Thread. But this is to answer specific question why it fails to compile. And by the way, compiler message gives you the answer already as it says that it can't assign to java.lang.Thread.State.
Upvotes: 1
Reputation: 2414
the problem is that you extend Thread and have no explicit super()
call in your constructor. as no no-arg constructor exists in Thread
you would need to explicitly call one of the public constructors in a super cal.
When you would implement Runnable
instead of extending Thread
you wouldn't have thos problem. and using new Thread(runnable)
you can construct a standard Thread that executes the given runnable instance.
Upvotes: 1
Reputation: 308763
I think extending java.lang.Thread
is a very bad idea. I doubt that you're going to provide behavior that's worth an extension.
I'm betting that you really want to implement java.lang.Runnable
and have it executed by java.lang.Thread
.
Upvotes: 6