Why do I get an error instantiating an interface?
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.
Imagine if one went into a store and asked for a device with a power switch. You didn't say whether you wanted a copier, television, vacuum cleaner, desk lamp, waffle maker, or anything. You asked for a device with a power switch. Would you expect the clerk to offer you something that could only be described as "a device with a power switch"?
A typical interface would be analogous to the description "a device with a power switch". Knowing that a piece of equipment is " a device with a power switch" would allow one to do some operations with it (i.e. turn it on and off), and one might plausibly want a list of e.g. "devices with power switches that will need to be turned off at the end of the day", without the devices having to share any characteristic beyond having a power switch, but such situations generally only apply when applying some common operation to devices that were created for some more specific purpose. When creating something from scratch, one would more likely wand a "copier", "television", "vacuum cleaner", or other particular type of device, than some random "device with a power switch".
There are some circumstances where one may want a vaguely-defined object, and really not care about what exactly it is. "Give me your cheapest device that can boil water". It would be nice if one could specify that when someone asks for an arbitrary object with "water boiling" ability, they should be offered an Acme 359 Electric Teakettle, and indeed when using classes it's possible to do that. Note, however, that someone who asks for a "device to boil water" would not be given a "device to boil water", but an "Acme 359 Electric Teakettle".
IUser
is the interface, you can't instantiate the interface.
You need to instantiate the concrete class that implements the interface.
IUser user = new User();
or
User user = new User();