Author Topic:   You can call the methods of a dead thread???!!!
Linda Xu
greenhorn
posted March 17, 2000 09:13 AM         
When study RHE's book, I found the statement in page 204 about Thread. It said:
You can call the methods of a dead thread

To test it, I try to compile the following code:


public class testThread {
public static void main(String[] agrs){
Thread thread = new MyRunnableClass();
thread.start();
thread.aMethod();
}
}

class MyRunnableClass extends Thread{
public void run() {
System.out.println("Linda's runnable");
}

public void aMethod() {
System.out.println("u always can call me");
}
}

Supprisingly, it doesn't compile! I got the error message in compile: testThread.java:7: Method aMethod() not found in class java.lang.Thread.

What's the metter? I can only override the method of Thread when I extend Thread class? Can anybody explain this?

Thanks!

maha anna
bartender
posted March 17, 2000 09:57 AM             
Linda,
Thread thread = new MyRunnableClass();

You are creating a MyRunnableClass and converting to it's superclass Thread. Since your aMethod() is defined in MyRunnableClass it doesn't show up when you see this MyRunnableClass object as a Thread object.

Instead, change the above code as
MyRunnableClass thread = new MyRunnableClass();
Everything will be ok.
regds
maha anna


[This message has been edited by maha anna (edited March 17, 2000).]

Howard Stern
ranch hand
posted March 17, 2000 11:09 AM             
Let me just extend a bit on what Maha had said.
If there was a method aMethod() defined in the class Thread and overrridden in the subclass then the program would have worked since the compiler would have seen the existence of aMethod() in the baseclass Thread.

However during runtime the aMethod() of the subclass would have been invoked because of late binding.


Jane Rozen
ranch hand
posted March 17, 2000 11:24 AM             
I think this quote from JLS (p.302)explains it further::
quote:

There are a few places in the Java language where the ACTUAL class of a referenced object affects program execution in a manner that cannot be deduced from the type of the expression. They are as follows:

Method invocation (§15.11). The particular method used for an invocation o.m(...) is chosen based on the methods that
are part of the class or interface that is the TYPE OF o. For instance methods, the class of the object referenced by the
run-time value of o participates because a subclass may override a specific method already declared in a parent class so that this overriding method is invoked. (The overriding method may or may not choose to further invoke the original overridden m method.)



*************
(I've got to learn how to use formatting in this software yet )

|