Posted on November 28, 2021 by Andrzej Dubaj
Object-oriented programming is primarily about isolating concepts into their own entities or, in other words, creating abstractions.
The clock has been implemented below using integer variables (the printing could be in a separate method, but that has not been done here).
Let’s create a ClockHand class that describes a clock hand, which contains information about its value, upper limit (i.e., the point at which the value of the hand returns to zero), and provides methods for advancing the hand, viewing its value, and also printing the value in string form.
Despite the previous example, one might deem it pointless to create an object containing only a number since the same could be done directly with int variables. However, that is not always the case.
Separating a concept into its own class is a good idea for many reasons. Firstly, certain details (such as the rotation of a hand) can be hidden inside the class (i.e., abstracted). Instead of typing an if-statement and an assignment operation, it’s enough for the one using the clock hand to call a clearly-named method advance(). The resulting clock hand may be used as a building block for other programs as well - the class could be named CounterLimitedFromTop, for instance. That is, a class created from a distinct concept can serve multiple purposes. Another massive advantage is that since the details of the implementation of the clock hand are not visible to its user, they can be changed if desired.
The way the program functions has become increasingly clearer. When you compare our program below to the original one that was made up of integers, you’ll find that the program’s readability is superior.
My site is free of ads and trackers. Was this post helpful to you? Why not