Let us see a real OOP example now.
Defining classes
Enough theoretical knowledge! We will come back to theories once we are comfortable writing in the OOP style. For years Java
has been the best programming language to learn about OOP, so we will be using Java for this example. AlgoDaily, however, tries to be as language-agnostic as possible, so we will also be adding some other languages such as Python and C++ for completeness.
Java has the keyword class
which defines a class. A class can be thought of as a blueprint for an object. For our keyboard and monitor example, a blueprint of keyboards and monitors will tell us what properties exist for a keyboard and monitor. For example:
- A keyboard must have a number of keys
- A keyboard must be able to send data via wired or wireless connection.
- A monitor must have a width and a height
Let's define the keyboard class in the simplest way possible. Create a file named Keyboard.java
and put the below text there.
As you can see, there are two properties (num_keys
and chars
) of the class
and 1 method (sendSignal
).
xxxxxxxxxx
public class Keyboard {
int num_keys;
char[] chars;
void sendSignal(char key) {
System.out.println("Signal sent : " + key);
}
}