Can I create an object for Interface?

后端 未结 7 889
庸人自扰
庸人自扰 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:44

    This is not creating the instance of Interface, it is creating a class that implements interface. So when you write:

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
    
        }
    };
    

    You are actually a creating a class that is implementing the Runnable interface. You need to follow all rules here, here, we are overriding the run method for Runnable. There is similar thing for abstract class also. We can test using an example:

    public abstract class AbstractClass {
        public void someMethod() {
            System.out.println("abstract class");
        }
    }
    

    and another class i.e. TestClass:

    public class TestClass {
        public static void main(String[] args) {
            AbstractClass abstractClass = new AbstractClass() {
                public void someMethod() {
                    System.out.println("concrete class method");
                }
            };
            abstractClass.someMethod();
        }
    }
    

    This will create the instance of a subclass in which we are overriding someMethod(); This program prints:

    concrete class method
    

    This proves we are creating the instance of subclass.

提交回复
热议问题