This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Extending Thread class

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread class implements Runnable interface. So when we wxtend Thread class Run() must be defined.
Following code sample is taken from mocktest in another section. In this code, run() is not implemented. Is not that a compile time error ? When I read the answer, it says code will run fine, but will not print anything.
 
Jan Hoppmann
Ranch Hand
Posts: 147
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread implements run(), but does nothing.
When extending classes, you don't have to implement their methods. You may overwrite them, but you don't have to. So a call to the run() method of a Bground object will call Thread's implementation of run(), which simply does nothing.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jan Hoppmann wrote:Thread implements run(), but does nothing.

Actually it does something. If you create a Thread with a Runnable as argument to the constructor, it will call run() on that Runnable. If you don't provide a Runnable then it does nothing. Part of the source code for Thread, taken from src.zip:
 
Hebert Coelho
Ranch Hand
Posts: 754
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have to tell what the method run does.

Take the code you wrote in the start method and put it in the run() method.

 
Michel ten Voorde
Greenhorn
Posts: 26
Android Linux Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think nirjari's question is whether extending the Thread class implies having to implement the run() method. This is not the case, your extended class inherits the run() method which is already in the Thread class. I think you confuse the 2 ways of defining a thread:

1) Extend the Thread class and override the run() method.
2) Implement the Runnable interface and implement the run() method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic