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

前端 未结 4 877
鱼传尺愫
鱼传尺愫 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:17

    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.

    0 讨论(0)
  • 2020-12-02 18:31

    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.

    0 讨论(0)
  • 2020-12-02 18:34

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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题