• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread and overriding

 
Asanka Vithanage
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();


}
}
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henry Wong
author
Marshal
Pie
Posts: 21420
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Henry Wong:
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


Although to be fair, that isn't the right answer!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic