Why do I get an error instantiating an interface?

后端 未结 6 1079
生来不讨喜
生来不讨喜 2020-12-08 06:22

I have a class and an interface, and when I try to instantiate the interface, I get an error:

Cannot create an instance of the abstract class or inter

6条回答
  •  误落风尘
    2020-12-08 07:03

    The error message seems self-explanatory. You can't instantiate an instance of an interface, and you've declared IUser as an interface. (The same rule applies to abstract classes.) The whole point of an interface is that it doesn't do anything—there is no implementation provided for its methods.

    However, you can instantiate an instance of a class that implements that interface (provides an implementation for its methods), which in your case is the User class.

    Thus, your code needs to look like this:

    IUser user = new User();
    

    This instantiates an instance of the User class (which provides the implementation), and assigns it to an object variable for the interface type (IUser, which provides the interface, the way in which you as the programmer can interact with the object).

    Of course, you could also write:

    User user = new User();
    

    which creates an instance of the User class and assigns it to an object variable of the same type, but that sort of defeats the purpose of a defining a separate interface in the first place.

提交回复
热议问题