3.4.4 How to Define an Interface

Defining interfaces is very similar to defining a class. The main difference is that all members in an interface are either methods or properties and do not declare any implementation.

The purpose of an interface is to ensure that the class that implements it has the members we declare in the interface. Interfaces allow us to change the behavior of an object, but we will cover more on that later. For that to work, however, we need to ensure that the object we want to change implements the interface that has the members we want the object to have. In that way, interfaces are a "contract". They don't really "do" anything they simply say, this object has this stuff.


So let's say we have already added an interface named ICleanable that represents things that are well...cleanable.

We then want all things that are "cleanable" to have certain functionality. In fact, we want to make sure they have that functionality. So in our project we have two things that are cleanable: the Restroom and the Booth. The thing we need to decide is what commonality those things share that we want both of them to have. Let's say that both things should need to have an OrganizeSupplies method and a property that returns if the object IsCleaned.


It is important to note that we do not care HOW the Restroom and the Booth implement this method and property we only care that they do. That being said, interfaces don't declare any implementation. To do this, we will define method and property stubs in the interface.

Defining Methods in an Interface

If we want to add a method to our interface it will look like this:

We can also add parameters to a method in an interface to ensure that implementing classes also take a parameter.

And we can also change the return type to ensure the method returns a specific type. Again, we don't care what the implementing method will return we just care that it returns a double.

There are two important things to note when defining a method in an interface:


Say we add public to an interface we will get this error:

Say we try to declare a method body we will get this error:

Defining Properties in an Interface

If we want to add a property to our interface it will look like this:

We can also add a setter to the property.

There are three important things to note when defining a property in an interface:

Say we change the return type to void we will get this error: