If I had:
interface Wibble {
public void speak();
}
And did:
Wibble test = new Wibble() {
@Override public void speak() {
System.out.println("Hello!");
}
};
test.speak();
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();
}
}
?
Top comments (3)
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).
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?
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'.