Can I create an object for Interface?

后端 未结 7 885
庸人自扰
庸人自扰 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 22:05

    Here's my understanding.

    An interface

    public Interface SomeInterface{
    }
    

    You can declare an Object for an interface.

    SomeInterface anObject;
    

    You cannot instantiate this object directly using this interface. However, let's say you have a class that implements this interface.

    public class SomeClass implements SomeInterface {}
    

    Then you can do this,

    anObject = new someClass();
    

    (This is conceptually of course (like pseudocode) actual code may vary depending on your classes and access modifiers etc.)

    I'll update as to why exactly we are doing this/what the point is as soon as I find out.

    Note: Some of this has been mentioned in above answers, just want the OP to know this whole thing too.

提交回复
热议问题