interface Int {
public void show();
}
public class Test {
public static void main(String[] args) {
Int t1 = new Int() {
public void
What this special syntax for anonymous inner classes does under the hood is create a class called Test$1
. You can find that class file in your class folder next to the Test class, and if you printed t1.getClass().getName()
you could also see that.
i think your object has nothing to do with the interface. If you comment out the whole interface, still you will get the same output. Its just anonymous class created. I think, unless you use the class "implements" you cant implement the interface. But i dunno how naming collision doesn't happen in your case.
You're defining an anonymous class that implements the interface Int
, and immediately creating an object of type thatAnonymousClassYouJustMade
.
This notation is shorthand for
Int t1 = new MyIntClass();
// Plus this class declaration added to class Test
private static class MyIntClass implements Int
public void show() {
System.out.println("message");
}
}
So in the end you're creating an instance of a concrete class, whose behavior you defined inline.
You can do this with abstract classes too, by providing implementations for all the abstract methods inline.