这是关于这种类的资料:
Anonymous Classes
You can declare an inner class without naming it. Here's yet another version of the now-tired Stack class, in this case using an anonymous class for its enumerator:
public class Stack {
private Vector items; ...//code for Stack's methods and constructors not shown... public Enumeration enumerator() {
return new Enumeration() {
int currentItem = items.size() - 1;
public boolean hasMoreElements() {
return (currentItem >= 0);
}
public Object nextElement() {
if (!hasMoreElements())
throw new NoSuchElementException();
else
return items.elementAt(currentItem--);
}
}
}
}Anonymous classes can make code difficult to read. You should limit their use to those classes that are very small (no more than a method or two) and whose use is well-understood (like the AWT event-handling adapter classes).我的理解是相当于:
WindowAdapter st = new WindowAdapter();
...addWindowListener (st);class WindowAdapter ( )
{
public void windowClosing ( WindowEvent e )
{
System.exit ( 0 ) ;
}
}
Anonymous Classes
You can declare an inner class without naming it. Here's yet another version of the now-tired Stack class, in this case using an anonymous class for its enumerator:
public class Stack {
private Vector items; ...//code for Stack's methods and constructors not shown... public Enumeration enumerator() {
return new Enumeration() {
int currentItem = items.size() - 1;
public boolean hasMoreElements() {
return (currentItem >= 0);
}
public Object nextElement() {
if (!hasMoreElements())
throw new NoSuchElementException();
else
return items.elementAt(currentItem--);
}
}
}
}Anonymous classes can make code difficult to read. You should limit their use to those classes that are very small (no more than a method or two) and whose use is well-understood (like the AWT event-handling adapter classes).我的理解是相当于:
WindowAdapter st = new WindowAdapter();
...addWindowListener (st);class WindowAdapter ( )
{
public void windowClosing ( WindowEvent e )
{
System.exit ( 0 ) ;
}
}
new XXX(){......}其实就是
class ThisClassDozntHaveAName extends/implemnts XXX{
public ThisClassDozntHaveAName(){
.....
}
.....
}extends/implements 取决于XXXX 是class 还是interface,
注意匿名类只能用一个interface,因为你不可能 new A, B, C(){...}
也不能 new ABC() implements/extends ANOTHER