• Post Reply Bookmark Topic Watch Topic
  • New Topic

What if a class extends thread and implements Runnable  RSS feed

 
fox reddy
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class ThreadBoth extends Thread implements Runnable {

public void run(){ System.out.print("hi "); }

public static void main(String [] args){
Thread t1 = new ThreadBoth();
Thread t2 = new Thread(t1);
t1.run();
t2.run();
}
}

Does class ThreadBoth act like a new Thread or iis just a class extending a superclass and runnable...?
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fox reddy wrote:class ThreadBoth extends Thread implements Runnable {

public void run(){ System.out.print("hi "); }

public static void main(String [] args){
Thread t1 = new ThreadBoth();
Thread t2 = new Thread(t1);
t1.run();
t2.run();
}
}

Does class ThreadBoth act like a new Thread or iis just a class extending a superclass and runnable...?


ThreadBoth can act as either a Thread, or a 'normal class' which implements Runnable. In your example code, t1 is a ThreadBoth acting like a Thread. t2 uses the ThreadBoth instance to act like a normal Runnable. Remember, when you use extends or implements your saying your code IS A. So because ThreadBoth IS-A Thread, it works like a Thread. Because ThreadBoth IS-A Runnable, it works like a Runnable.

Also note that there is no distinction on which 'run()' method gets override or executed. Both Thread's and Runnable's run() method are overriden at the same time.

Also not that all Thread subclasses implicitly implement Runnable, because Thread itself implements Runnable (Thread IS-A Runnable, so any sub type of Thread IS-A Runnable as well).
 
Fred Hamilton
Ranch Hand
Posts: 684
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Steve, this thread caught my eye because of the similarities to our discussion the other day.

perhaps the first post here was just hypothetical question, but it seems to me there is no point in having a class both extend thread and implement runnable. If the class already implements Runnable, then there is nothing that adding extends thread allows you to do that you couldn't just as easily (or almost as easily) do without extends thread.

agreed?
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree. There really isn't any reason to both extend Thread and implement Runnable. You gain nothing from it, and usually gain nothing from using Thread that you don't get in using the Runnable.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!