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

前端 未结 4 876
鱼传尺愫
鱼传尺愫 2020-12-02 17:50
interface Int {
    public void show();
}

public class Test {     
    public static void main(String[] args) {
        Int t1 = new Int() {
            public void         


        
4条回答
  •  温柔的废话
    2020-12-02 18:37

    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.

提交回复
热议问题