Can I create an object for Interface?

后端 未结 7 882
庸人自扰
庸人自扰 2020-12-14 21:32

Is it possible to create an object for an interface? If yes, how is it done? According to my view the following code says that we can:



        
7条回答
  •  自闭症患者
    2020-12-14 21:43

    Is it possible to creating object for an interface?

    No. The code you've shown creates an object from an anonymous class, which implements the interface. Under the covers, the JVM actually creates a class implementing the interface, and then creates an instance of that class.


    The "anonymous" class generated will actually have a name, based on the name of the class in which this code appears, for instance YourClass$1 or similar. E.g.:

    public class AnonymousName {
        public static final void main(String[] args) {
            Runnable r = new Runnable() {
                public void run() {
                }
            };
    
            System.out.println(r.getClass().getName());
        }
    }
    

    ...outputs

    AnonymousName$1

    (At least on Oracle's JVM; I don't know if the naming convention is in the JLS or if it's JVM-specific behavior.)

提交回复
热议问题