How to Practice Object-Oriented Programming

Elnur
2 min readJul 31, 2021

--

Whenever we want to learn something, we need to practice it. For example, if we learn the sorting algorithms, we go and solve some problems with this algorithm. Practicing algorithms is a little easy since there are lots of great websites for that. But how are we going to practice Object-Oriented Programming (OOP) ?

OOP is one of the significant topics of programming. It helps us to write more clean, structured and organized code. Experienced programmers would always use OOP concepts to have well-written code.

Of course, the best way of practicing OOP is starting to use them in your projects, but most of the projects are much bigger, so we need some little projects.

What we need is “simulating” the real world. It might seem weird, but I am going to explain what I mean.

As an example, let’s say we are simulating a computer. Our computer has a monitor, case, keyboard and mouse. We are going to print some messages to the console as if it is happening in real life. This is why I am calling it “simulating”.

We first create our main class, Computer:

Note: I am using c# as a programming language, but it does not matter what you want to use as long as it is OOP language

We also have four different classes for our monitor, case, keyboard and mouse.

We will declare instance variables to represent these devices as our computer’s part:

We also need a constructor to set them. Think of it as we plug them in:

All of our devices should be able to turn on, so we add TurnOn() method to them:

What do we do when we want to turn on the computer in real life ? We press the power button in our computer

In our Computer class’ TurnOn() method we call the case’s PressPowerButton() method:

Before running our program, let’s update our Case class’ TurnOn() method to turn on other devices too. This time, it will take other devices as a parameter and will case their TurnOn() method.

Now let’s create a ComputerSimulator.cs class to test what we have done till now:

The output is like this:

Pressing the power button
Monitor is turning on
Keyboard is turning on
Mouse is turning on

OOP is very deep topic and understand it take some time. So, be patient and start to practice them by using this technique.

Thanks for reading till here. I hope it was helpful to you :).

--

--