Reputation: 3955
I am examining code here which uses inheritance and threads.
There is a BaseCom and ServerCom class as below. The ServerCom class extends the BaseCom class. The BaseCom class implements an interface called Com.
public class BaseCom implements Com
{
protected final Thread thread;
protected final InetSocketAddress socketAddress;
public BaseCom(InetSocketAddress socketAddress)
{
System.out.println("BaseCom CONSTRUCTOR!!!!");
this.socketAddress = socketAddress;
thread = new Thread(() -> run(socketAddress));
}
@Override
public void start()
{
System.out.println("HELLO FROM BaseCom start method!!!!");
thread.start();
}
protected void run(InetSocketAddress socketAddress)
{
System.out.println("HELLO FROM BaseCom run!!!!");
}
//.... more stuff .... not shown here
}
lll
public class ServerCom extends BaseCom
{
public ServerCom(InetSocketAddress socketAddress, long timeOutMs)
{
super(socketAddress);
System.out.println("ServerCom CONSTRUCTOR!!!!");
}
@Override
protected void run(InetSocketAddress socketAddress)
{
System.out.println("ServerCom run method!!!!");
}
// ... more stuff.. not shown here
}
Why is it when I run the following code below from a main function, that actually the run method of the ServerCom class gets executed and not that of the basecom class?
The fact that line thread = new Thread(() -> run(socketAddress));
is inside the BaseCom class and not the ServerCom class, would make me think that it should be the Basecom run method which gets called.
connectorA = new ServerCom(socketAddressA, 1000000);
connectorA.start();
Upvotes: 1
Views: 87
Reputation: 20185
The call to run(...)
is resolved at runtime (dynamic dispatch). Since the actual type of this BaseCom
is ServerCom
, ServerCom
's run(...)
is executed. There is no way to enforce that BaseCom
's run(...)
-method is called if it is overridden (since it is overridden the original method is inaccessible).
The problem is not related to multithreading.
Upvotes: 4