DEV Community

Calin Baenen
Calin Baenen

Posted on

Is an anonymous inner-type (AIT) the equivalent of creating a class instance from a class that implements an interface?

If I had:

interface Wibble {
    public void speak();
}
Enter fullscreen mode Exit fullscreen mode

And did:

Wibble test = new Wibble() {
    @Override public void speak() {
        System.out.println("Hello!");
    }
};
test.speak();
Enter fullscreen mode Exit fullscreen mode

would that be the same as if I did:

class Wobble implements Wibble {
    @Override public void speak() {
        System.out.println("Hello!");
    }
}

class Main {
    public static void main(String[] args) {
        Wibble test = new Wobble();
        test.speak();
    }
}
Enter fullscreen mode Exit fullscreen mode

?

TL;DR Is making an AIT the same as making an instance of the interface, or an instance of a class that implements it, OR is it more similar to making a new class entirely?

Top comments (3)

Collapse
 
alainvanhout profile image
Alain Van Hout

You're then making an entirely new class. Even more so: if you do that inside a method, which you call multiple times, then you will be creating multiple new classes (they might be identical in structure, but they will have separate identities in the JVM).

Collapse
 
baenencalin profile image
Calin Baenen

Does it act as a class, or an instance of a new class (that's presumably created OTS)?
Since I can use non-static methods just fine, and I can't (re-)instantiate it?

Collapse
 
alainvanhout profile image
Alain Van Hout • Edited

The thing you create there is a new instance, of a class that's also created there and then. Without some additional magic (using 'reflection') you won't be able to create a new instance of that class, or (easily) make use of its public static methods (except of course from inside that newly created class instance).

In case you're familiar with JavaScript, this can be thought of as somewhat equivalent to an 'anonymous function'.