Question 14 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(); } }
What is the result of attempting to compile and run the program? a. Prints: A b. Prints: B c. Prints: AB d. Prints: BA e. Compiler error f. Run time error g. None of the above
The answer is a. But I don't understand why isn't B's run is being executed. However if i remove A's run method B's run method is run. I guess that A's run is overridding B's run. How this overriding takes place. [ May 17, 2003: Message edited by: Anupam Sinha ]
chi Lin
Ranch Hand
Joined: Aug 24, 2001
Posts: 348
posted
0
changes in main() as following, A a1 = new A(new B()); a1.start();
output will be A if run() in class A is active or B if run() is commented out.
HTH [ May 16, 2003: Message edited by: chi Lin ]
not so smart guy still curious to learn new stuff every now and then
Anupam Sinha
Ranch Hand
Joined: Apr 13, 2003
Posts: 1088
posted
0
Thanks Chi Lin for the reply but I was aware of that. What I am asking is that when the Thread's constructor has been supplied with a runnable object reference why isn't that runnable object's run method is being run.
Maulin Vasavada
Ranch Hand
Joined: Nov 04, 2001
Posts: 1865
posted
0
hi anupama okay. the code for the Thread's run() must be like, public void run() { if ( myRunnable != null ) { myRunnable.run(); } } where myRunnable is the Runnable object which might have been passed in Thread()'s consturctor. now, when u implement run() in class A, that default implementation gets OVERRIDDEN. so it doesn't matter that u passed the Runnable to the thread's constructor... but when u remove the implementation of run() from A, it uses parent's run() method implementation and so if u had passed the Runnable object to the constructor then it would invoke run() on that... hope i'm able to make a point. regards maulin
Hi Maulin Well you really really helped me explain this to me and that too in a nice manner. Thanks a lot. One more thing my name is not Anupama its Anupam Sinha. [ May 17, 2003: Message edited by: Anupam Sinha ]
Maulin Vasavada
Ranch Hand
Joined: Nov 04, 2001
Posts: 1865
posted
0
hey sorry i misread ur name. i shd stop replying at 2 am in the morning (i 'm in CA) regards maulin