aspose file tools*
The moose likes Beginning Java and the fly likes thread and overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "thread and overriding" Watch "thread and overriding" New topic
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: 24187
    
  34

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: 18989
    
  40

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: 24187
    
  34

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!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: thread and overriding