| Author |
thread and overriding
|
Asanka Vithanage
Ranch Hand
Joined: Oct 24, 2008
Posts: 59
|
|
can any body explain the reason for answer of following code it gives 1 as output.i can't understand what is really happen class B extends Thread { B(){} B(A a){} public void run(){ System.out.println("1"); } } class A extends B { A(){} A(B a){} public void run(){ System.out.println("2"); } public static void main( String as[]){ Thread a =new B (new A()); a.start(); } }
|
SCJP 1.5 (94%)
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24054
|
|
Thread's "start()" method calls the Thread's "run()" method. The default run() will look to see if the Thread was constructed with a Runnable as an argument; if so, it will call the Runnable's run(), or otherwise, just return. You've overridden that default behavior to just print "1". The A object actually is not used for anything. start() calls B.run() which prints "1" and exits. Pretty simple, actually.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16687
|
|
You already asked this question -- and got an answer a while ago... http://www.coderanch.com/t/417778/java-programmer-SCJP/certification/java-threads Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24054
|
|
Although to be fair, that isn't the right answer!
|
 |
 |
|
|
subject: thread and overriding
|
|
|