Abstraction

Learn how interfaces help in achieving abstraction.

We'll cover the following

Interfaces and abstraction

Interfaces help make parts of programs independent from each other. This is called abstraction. For example, a program that deals with musical instruments can be written primarily by using the MusicalInstrument interface, without ever specifying the actual types of the musical instruments.

A Musician class can contain a MusicalInstrument without ever knowing the actual type of the instrument:

class Musician {
    MusicalInstrument instrument;
    // ...
}

Different types of musical instruments can be combined in a collection without regard to the actual types of these instruments:

MusicalInstrument[] orchestraInstruments;

Most of the functions of the program can be written only by using this interface:

bool needsTuning(MusicalInstrument instrument) {
    bool result;
    // ...
    return result;
}
void playInTune(MusicalInstrument instrument) {
    if (needsTuning(instrument)) {
        instrument.adjustTuning(); 
    }

    writeln(instrument.emitSound()); 
}

Abstracting away parts of a program from each other allows making changes in one part of the program without needing to modify the other parts. When implementations of certain parts of the program are behind a particular interface, the code that uses only that interface does not get affected.


Get hands-on with 1400+ tech skills courses.