How to call enclosing class method ?

L

lonelyplanet999

Hi,

When I run below code the output is

MyThread foo

New
===
MyThread bar baz
foo
bar

The first line "MyThread foo" is output by t.start(), the line
"MyThread bar baz" is output by t1.run() & t1.run("don't care this
string").

The line "foo" is output by t.run() while the line "bar" output by
t1.start().

If I want to run public void run(String s) method of MyThread from
instance t (with an implicit inner class), is that possible ? If so,
how ?

Tks :)

===============================
class MyThread extends Thread {
MyThread() {
System.out.print(" MyThread");
}
public void run() {
System.out.print(" bar");
}
public void run(String s) {
System.out.println(" baz");
}
}

public class Ch9q19a {
public static void main (String [] args) {
Thread t = new MyThread() {
public void run() {
System.out.println(" foo");
}
};
t.start();
t.run();

System.out.println("\nNew\n===");
MyThread t1 = new MyThread();
t1.run();
t1.run("don't care this string");
t1.start();
}
}
 
J

John C. Bollinger

lonelyplanet999 wrote:
[...]
If I want to run public void run(String s) method of MyThread from
instance t (with an implicit inner class), is that possible ? If so,
how ?

The term you want is "anonymous inner class". The fact that it is
anonymous has no bearing on normal Java inheritance. The point of
confusion may be that the type of variable t is Thread, but that in no
way prevents its value from being a reference to a MyThread (because
MyThread is a subclass of Thread). Since Thread does not declare the
method in question, however, you have to cast t in order access it:

((MyThread) t).run("very fast");

You could also cast t to MyThread and store it in a reference variable
of that type, then invoke run(String) on that.


John Bollinger
(e-mail address removed)
===============================
class MyThread extends Thread {
MyThread() {
System.out.print(" MyThread");
}
public void run() {
System.out.print(" bar");
}
public void run(String s) {
System.out.println(" baz");
}
}

public class Ch9q19a {
public static void main (String [] args) {
Thread t = new MyThread() {
public void run() {
System.out.println(" foo");
}
};
t.start();
t.run();

System.out.println("\nNew\n===");
MyThread t1 = new MyThread();
t1.run();
t1.run("don't care this string");
t1.start();
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,189
Members
46,736
Latest member
zacharyharris

Latest Threads

Top