Java – declare anonymous inner classes
•
Java
rb.addActionListener(new ActionEvent(ae) {
rb.addActionListener(new ActionEvent(ae) { public void actionPerformed(ActionEvent ae) { NowCall(ae); } });
Other ways
Thread th=new Thread(Runnable r) { public void run() { // do something } }; // notice the ending of above 2 snippets
Seeing these two, I'm really confused There seems to be no exact pattern for declaring an anonymous inner class
Please explain the syntax of anonymous inner classes
Solution
The second is invalid, as far as I know and tested
More commonly, create a new runnable implementation:
Thread th=new Thread(new Runnable() { @Override public void run() { // This implements Runnable.run } });
Now you can override the run method of ordinary threads:
Thread th=new Thread() { @Override public void run() { // This overrides Thread.run } };
... but I personally prefer to specify runnable separately when creating threads
Now the only difference you notice at the end is whether the expression is used as a parameter (for example, for addactionlistener method or thread (runnable) constructor, or whether it is only directly assigned to a variable Think of the new typename () {...} as a single expression. It's just the difference:
Thread th = expression;
and
Thread th = new Runnable(expression);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码