McWalter.org :: Nondefault pseudoconstructors for anonymous classes


Because they don't have names, anonymous classes can't have constructors. This can be annoying.

In java 1.1, a partial solution was provided - all classes can have an instance initialiser, a block of code that runs when an instance is constructed - this works essentially like a default (i.e. noarg) constructor. This is better, but it still doesn't allow one to define constructors with arguments.

This page shows a little trick were one can simulate this functionality. The example below shows a non-anonymous baseclass which a non-default constructor that then calls a regular method. The anonymous subclass then overrides this method.

The example below shows an anonymous class that subclasses MouseAdapter that features a one-arg pseudoconstructor.


// AnonPseudo.java
// Copyright (c) 2002, 2003 W.Finlay McWalter
// Licence: GPL v2

import java.awt.*;
import java.awt.event.MouseAdapter;

abstract class MyMouseAdapter extends MouseAdapter {
    MyMouseAdapter(Window w){
        pseudoConstructor(w);
    }

    abstract void pseudoConstructor(Window w);
}

public class AnonPseudo {
    public static void main(String [] args){
        Frame f = new Frame();

        MouseAdapter m = new MyMouseAdapter(f) {
            void pseudoConstructor(Window w){
                System.out.println("pseudoconstructor called "+w);
            }
        };
    }
}