Engineer999
Engineer999

Reputation: 3955

Java inheritance with threads confusion

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

Answers (1)

Turing85
Turing85

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

Related Questions