A Class Interface is a contract of sorts that can be fulfilled by any class that can supply the contract’s required functions. This lets one class refer to an object who implements the Class Interface without having to know what actual class it is.
For example: class FruitBowl is responsible for building a fruit salad. You have a class Orange that has a method GetSlice() that returns an instance of Slice. FruitBowl calls the instance’s GetSlice() method and stores the result.
That’s great if your salad consists solely of oranges. But what about other fruit - or even things that aren’t fruit? That’s where the Class Interface comes in handy.
Your Class Interface contains a single method, lifted directly from your Orange class: GetSlice() as Slice. Class Interfaces only define the contract, so they don’t contain any code; it’s the responsibility of the class that implements the interface to do the actual work. We’ll call the interface SliceProvider.
Your Orange class contains a method with the exact same signature as the SliceProvider interface and that actually returns a result. It also declares to the compiler that it implements the interface so the complier can do proper type checking.
Your FruitBowl class should now be altered to accept class instances that implement the SliceProvider interface (instead of just Oranges). It then calls the methods specified in the class interface, which are handled by the class instance itself.
Now, wherever you want a different ingredient in your salad, you create a new class (say, Apple), supply it with the proper methods to implement the SliceProvider class, tell the complier that it does this, and you’re ready to go. FruitBowl doesn’t need to know about the Apple class, all it cares about is that it is working with instances that implement the SliceProvider interface.
Class Interfaces are a great example of polymorphism, where an object takes on different behaviors depending on context. Classes may implement multiple class interfaces - in our example, the Orange and Apple classes might also implement the ConvertToJuice class interface, and the Orange might also implement the EmitZest interface. Once you get your head around them, you’ll start seeing uses for class interfaces everywhere!