Skip to main content

Interface vs implementation

Short answer

Interface defines what operations a class provides (signatures, contracts) without revealing how they work. Implementation is the hidden code and data that realize those operations. Separating them enables encapsulation and loose coupling: clients depend only on the stable interface, so implementations can change freely.

Explain the concept of interface and implementation in object oriented design and implementation. (How interface differ from implementation? Explain the concept of interface and implementation in any object oriented programming languages.)

Concept

  • Interface: the what, the public face of a class or component. It declares the set of operations (names, parameters, return types and contract) that other objects can use. It says nothing about how they work. In UML it is a classifier with <<interface>>; in Java it is the interface construct.
  • Implementation: the how, the actual code and data (private fields, algorithms) that carry out the operations. It is hidden from the clients.

Separating them is the basis of encapsulation, abstraction and loose coupling: clients depend only on the interface, so the implementation can be changed or replaced without changing the clients.

   Client ----uses----> <<interface>>
                         Shape
                         + area()
                          ^     ^
                          :     :  (realization)
                      Circle   Rectangle
                      (implementations)

Difference

PointInterfaceImplementation
DescribesWhat can be doneHow it is done
ContentOperation signatures (and constants)Code, attributes, algorithms
VisibilityPublicMostly private/hidden
InstancesCannot be created directlyConcrete classes create objects
ChangeShould be stableCan change freely
MultiplicityA class can implement many interfaces, and one interface can have many implementationsEach implementation is one concrete class

Example in Java

interface Shape {                    // interface
    double area();
}
class Circle implements Shape {      // implementation 1
    private double r;
    Circle(double r) { this.r = r; }
    public double area() { return Math.PI * r * r; }
}
class Rectangle implements Shape {   // implementation 2
    private double w, h;
    Rectangle(double w, double h) { this.w = w; this.h = h; }
    public double area() { return w * h; }
}
// Client depends only on the interface
Shape s = new Circle(2);
System.out.println(s.area());

In C++ the same is done with an abstract class that has pure virtual functions (virtual double area() = 0;), and in C# with the interface keyword.

✓ Answer checked by Claude Sonnet 5.5

All Object Oriented Analysis and Design chapter 4 questions →