C++ Interface

C++ Interface


C++ Interfaces

Interfaces are similar to abstract classes but different in their functionality. In interfaces, none of the methods are implemented means interfaces defines methods without body

  • Definitions
  1. abstract methods: Methods that are declared, with no implementation
  2. abstract class: A class with abstract methods, not meant to be instantiated
  3. interface: A named collection of method definitions (without implementations)

 

  • Every method declared by an object specifies the method’s name, the object/value it takes as parameters, and the method's return value. This is known as the operation signature.
  • The set of all signatures defined by an object’s method is called the interface to the object. An object’s interface characterizes the complete set of requests that can be sent to an object.
  • An interface is like an abstract class that cannot be instantiated. Interfaces are better suited to situations in which your applications require many possibly unrelated objects types to provide certain functionality.
  • Explicitly implementing the interface in a class enables us to define a set of methods that are mandatory for that class.
  • Interface definition begins with the keyboard interface.
  • For Example: Food is an abstract class. Can you make an instance of food? No, of course not. But you can make an instance of an apple or a steak or a peanut butter cup, which are types of food. Food is an abstract concept; it shouldn’t exist. Skills are interfaces. Can you make an instance of a student, an athlete, or a chef? No, but you can make an instance of a person, and have that person take on all these skills. Deep down, it’s still a person, but this person can also do other things, like study, sprint, and cook.

Abstract Classes & Interfaces

  • An interface cannot implement any methods, whereas an abstract class can
  • A class can implement many interfaces but can have only one superclass (abstract or not)
  • An interface is not part of the class hierarchy. Unrelated classes can implement the same interface

The Syntax of Abstract Classes & Interfaces are as follows:

 

  • abstract class:

             public class Apple extends Food { … }

  • interface: 

            public class Person implements     

            Student, Athlete, Chef { … }

 

Example: Program for abstract class is as shown below:

Output

When to use Interface

  • Useing an interface immutable contract is really intended.
  • Interfaces are better suited in situations when your applications require many possibly unrelated object types to provide certain functionality.
  • Interfaces are better suited in situations in which you do not need to inherit implementation from a base class.
  • The Interface can be used for multiple Inheritance.