The separation of a class’s interface against its implementation is the core principle behind encapsulation and data hiding, ensuring that only the object itself control its own actions.
A class declaration combines the external interface (its non-private methods) with an implementation of that interface (the code that carries out the behaviour).
The interface defines a class’s visibility to others.
- Interface defines what an object can do, but doesn’t actually do it
- Implementation carries out the operation declared in the interface
- The class design specifies the interfaces to enable an object to be instantiated and operated properly
- The Interface should completely describe how users of the class interact with the class
- The behaviour of an object must be invoked by a message using one of the provided interfaces
- An object’s attributes and behaviour is controlled by sending messages to the object
- Messages consist of the target object’s name, the desired behaviour to use (i.e. the method) and any parameters required by the behaviour
For example, let’s take the example of increasing a motorbike’s speed.
The rider doesn’t care about the internal working they just want to increase the speed and so they twist the throttle to get the desired behaviour.
The throttle is the interface between the rider (the calling/invoking object) and the engine (the called object).
In this case, the message would be Motorbike.setSpeed(66); This is the interface.
Internally, the engine of the bike is doing all manner of things, e.g. supplying fuel from the petrol tank to the injectors, the injectors electronics controlling the amount of fuel supplied to the combustion chamber, the spark plugs igniting the fuel mix at the right time, opening the valves to exhaust the spent fuel, etc.
All of these actions are separated from the rider, who just wants to go faster. We don’t want him to do any of the internal (private) methods, as this could have disastrous effects!
We therefore separate interface from implementation.