wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes java threads 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 "java threads" Watch "java threads" New topic
Author

java threads

Asanka Vithanage
Ranch Hand

Joined: Oct 24, 2008
Posts: 59
the following code gives 1 as output
please is there any body can explin the logic and correct thinking pattern to get that answer

class B extends Thread {
B(){}
B(B 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%)
Rakesh Rajagopalan
Ranch Hand

Joined: Sep 19, 2006
Posts: 59
Hi,

B extends Thread and A extends B. Hence, A IS-A B and B IS-A Thread. When you say: Thread a = new B(new A());, JVM chooses Object B at runtime and constructs a new B. Since B's constructor can take a 'B' Object and A IS-A B, therefore the run() method of B is called and the output is 1.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Welcome to JavaRanch. Please use code tags when you post code.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

Asanka this is because the internal implementation of the run method in Thread class. The internal implementation of Thread class looks like this




So when you use this code


The run method of Thread class is called and it calls the run method of MyRunnable class.

But in you code the run method of B will be called and it doesn't calls the run method of A class. Infact, it wastes the Runnable passed to it as a parameter

B(B a)
{//does nothing}

This constructor declaration should have been like this

B(Runnable r)
{
super(r);
}


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: java threads
 
Similar Threads
need help with inner classes
A question for Beginners - 3
java threads
thread
thread and overriding