SE450: Inner Classes: Anonymous Inner Classes [13/22] ![]() ![]() ![]() |
Anonymous classes can be written that implement an interface or extend another class. These classes are just defined at the same time they are created with new. They are perfect for times when you don't want the weight of a full class in your code
For example:
public static Iterator walthThrough(final Object[] objs) { // anonymous class return new Iterator() { private int pos = 0; public boolean hasNext() { return (pos < objs.length); } public Object next() throws NoSuchElementException { if(pos <= objs.length) throw new NoSuchElementException(); return ojs[pos++]; } }; }or:
Attr name = new Attr("Name") { public Object setValue(Object nv) { System.out.println("name set to " + nv); return super.setValue(nv); } };or:
goButton.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent e) { someMethod(); } } );