my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes override Thread.start() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "override Thread.start()" Watch "override Thread.start()" New topic

override Thread.start()

Simon Cockayne
Ranch Hand

Joined: Dec 09, 2000
Posts: 214

1) Gives output:


Which is as one should expect.

x.start() starts the thread which runs the code in the run() method.

2) But...rename startZ to start, i.e. overriding Thread.start() gives output:


I.e. A new thread is NOT started.

So, questions:

Why would one want to override Thread.start()?

Why isn't it marked final?



SCJP 1.4 (93%)<br />SCJD (In progress. It can run, but it can't hide...)
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Well, whenever you override something, you're expected to do it in a way that does not violate the stated API of the original method. The API says start() is supposed to start a thread; therefore you shouldn't override it in a way that does not start a new thread. But Sun can't prevent every possible coding mistake you might make. The decided to give us the power to revise behavior of methods in our classes; it's our responsibility to use this power sensibly.

Here's one possible example of an override of start() that does something potentially useful, but still fulfills the requirements of the API:

The key is that at some point, amidst doing whatever other functionality you want to add, you call the original method you're overriding. Depending on what class and method you're dealing with, in some cases you may not need to call the original method while overriding; in other cases, it's your only sensible option.

"I'm not back." - Bill Harding, Twister
Simon Cockayne
Ranch Hand

Joined: Dec 09, 2000
Posts: 214
Hi Jim,

Thanks for the swift reply.

What you say sure makes sense...

I was limiting my thinking to doing initialising and so forth in the thread's constructor.

However, I am now the wiser (note - not the wisest).


I agree. Here's the link:
subject: override Thread.start()
It's not a secret anymore!