rb.addActionListener(new ActionEvent(ae) {
public void actionPerformed(ActionEvent ae) {
nowCall(ae);
}
});
Another way
Thread th=new Thread(Runnable r) {
public void run() {
// do something
}
};
// notice the ending of above 2 snippets
I am really confused seeing these two.It seems there is no exact pattern to declare an anonymous inner class.
please explain the syntax for anonymous inner class.
The second isn't valid, as far as I can see and test.
What would be more common would be to create a new Runnable implementation:
Thread th=new Thread(new Runnable() {
@Override
public void run() {
// This implements Runnable.run
}
});
Now you could just override the run
method of a normal thread:
Thread th=new Thread() {
@Override
public void run() {
// This overrides Thread.run
}
};
... but personally I prefer specifying the Runnable
separately when creating a thread.
Now the difference that you noticed at the end is simply whether the expression is used as an argument (e.g. to the addActionListener
method or the Thread(Runnable)
constructor, or whether it's just assigned directly to the variable. Think of the whole new TypeName() { ... }
as a single expression, and it's just the difference between:
Thread th = expression;
and
Thread th = new Runnable(expression);
There is the difference that in the first case your passing it as an parameter to a method and in the second example you're storing it in a local variable.
So you can't really compare both examples against each other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With