Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This appears to create an object from an interface; how does it work?

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();
    }
}
like image 957
shashi27 Avatar asked Oct 16 '10 04:10

shashi27


2 Answers

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

like image 80
Pops Avatar answered Nov 06 '22 00:11

Pops


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.

like image 25
oksayt Avatar answered Nov 06 '22 02:11

oksayt