views:

89

answers:

4
interface Int {
    public void show();
}

public class Test {     
    public static void main(String[] args) {
        Int t1 = new Int() {
            public void show() {
                System.out.println("message");
            }
        };

        t1.show();
    }
}
+7  A: 

You're defining an anonymous class that implements the interface Int, and immediately creating an object of type thatAnonymousClassYouJustMade.

Lord Torgamus
This is really useful for event handlers (such as those that use the ActionListener interface).
pst
+2  A: 

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.

Thilo
+1  A: 

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.

oksayt
A: 

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.

sivabalan
The anonymous class definitely implements the interface, and `t1 instanceof Int` will be true.
Thilo