Freitag, 16. November 2012

Overloading with anonymous classes in Java

Most examples of anonymous classes in Java use interfaces but it is also possible to create an anonymous class by overloading a normal class. Here is an example:
class inner
{
    int x;
    inner (int x) { this.x = x; }
    int next () { return x + 1; }

    public static void main (String[] args)
    {
        inner i = new inner (42);
        inner j = new inner (42) {
                { this.x = x + 1; }
                int next () { return x - 1; }
            };

        System.out.println (i + ": " + i.x);  // -> 42
        System.out.println (j + ": " + j.x);  // -> 43

        System.out.println (i + " next: " + i.next());  // -> 43
        System.out.println (j + " next: " + j.next());  // -> 42
    }
}
And here is a bit more complicated example: an anonymous class derived from an abstract class implementing an interface based on another interface.
// outer class
class run
{
    // named inner interface
    interface Named
    {
        String name ();
    }

    // named inner interface extending another interface
    interface Column<T> extends Named
    {
        T get ();
        void set (T value);
    }

    // named abstract class implementing an interface
    abstract class StringColumn implements Column<String>
    {
        public abstract String name ();
        int length;
        StringColumn (int length) { this.length = length; }
        String value;
        public String get () { return value; }
        public void set (String value) { this.value = value; }
    }

    run () 
    {
        // anonymous class extending the abstract class
        Column<String> column = new StringColumn (100) {
                public String name () { return "FIRSTNAME"; }
            };

        column.set ("Sascha");

        System.out.println (column.name() + ": " + column.get());
    }

    public static void main (String[] args)
    {
        new run ();  // -> FIRSTNAME: Sascha
    }
}

Keine Kommentare: