Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread Question from Dan's Mock exam

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a question from Dan's Mock exam.

class A extends Thread {
public A(Runnable r) {super(r);}
public void run() {System.out.print("A");}
}
class B implements Runnable {
public void run() {System.out.print("B");}
}
class C {
public static void main(String[] args) {
new A(new B()).start();
}}

According to my understanding since we are passing an instance of B as Runnable target when we call start() method "B" should be printed but the answer is "A".

Could someone please explain me?

Thanks

Vydhehi
 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From the java API start()Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Thus, it will invoke the Threads run method. The Thread A has two potential run methods- the base class which will call start on Runnable B which prints B, and the derived class A which will call the run which prints A.

Which of these two methods will be invoked when the start method is called? It is bound dynamically, and actually is of type A, not Thread, so binds to the A method, and prints A.

Consider these as well:


This will print B.



If you comment out this line:


Then B is printed. It is no longer being dynamically bound- the run method is not overridden.
[ September 24, 2004: Message edited by: Tom Tolman ]
 
Yeah, but how did the squirrel get in there? Was it because of the tiny ad?
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic