Anonymous Classes in Java

Java still lacks anonymous functions (as far as I know). It does have anonymous classes though. They’re used often in conjunction with the ActionListener class. In the below example I create an anonymous class using an interface. Have a look at this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.awt.*;
import java.applet.*;
 
public class Test extends Applet {
 
  public void init(){
    setSize(500,500);			  
  }
 
  Graphics g;
  public void paint (Graphics graphics) {
    g = graphics;
 
    // anonymous class of type ZShape, implements the render() function
    repeat(new ZShape() {
      public void render() {
        g.setColor(new Color((int)(Math.random() * 0xFFFFFF)));
        g.fillOval((int)(Math.random() * 500),
        (int)(Math.random() * 500),
        30,30);
      }
    });
  }
 
  public interface ZShape{
    public void render();
  }
 
  private void repeat(ZShape z){
    for (int i = 0; i<100; i++){
      z.render();
    }
  }
}

This example is visually boring, it just draws a bunch of randomly colored circles to the screen. But if you’ve never seen anonymous classes before, its interesting. You can use classes or interfaces, but the syntax basically works like this:

new ClassOrInterface(){
  // implementation
}

…you can then pass this class to a function or a constructor or store it in a variable. Pretty interesting stuff.



 
 
 

Leave a Reply

Spam protection by WP Captcha-Free