Examples in other languages
In most modern programming languages, OOP is natively supported, so there is most likely a keyword named class
and/or new
in your favorite language. Most languages also contain some simplified notation for classes. For example, you can access a property or call a member function of an object using the .
(dot) operator. An additional benefit of learning the concept of OOP is that it will help you write code with good practices in many modern languages.
We will be showing you the most common C++
, Python
, and Javascript
languages with the above example.
Below is the C++ code for the above example. Java recommends that you create each new class
in a separate file or they cannot be public (more on this when we discuss encapsulation in a later lesson). But in C++, you can create any number of classes in the same file. Also, your main
method is outside of a class. This is because C++ is based on a Structured Programming Language which is why it has a lot of features that make the language less OOP supported.
1#include <iostream>
2
3using namespace std;
4
5class Keyboard {
6public:
7 int numKeys;
8 char *keys;
9
10 void sendSignal(char ch) {
11 cout << ch << endl;
12 }
13};
14
15int main() {
16 Keyboard keyboard;
17 keyboard.numKeys = 26;
18 cout << keyboard.numKeys << endl;
19 keyboard.sendSignal('a');
20}
Below is Python code for the same Keyboard. Python is a loosely typed language and is a little farther from OOP compared to C++ and Java. The syntax might seem weird at first. Python always needs a default value to be set explicitly for classes. In Java and C++, all data types have an implicit default value (e.g., 0 for integers and "" for strings).
1class Keyboard:
2 # We will talk about this weird __init__ method in next lesson when we introduce constructors.
3 def __init__(self):
4 self.numKeys = 0
5 self.chars = []
6
7 def sendSignal(ch):
8 print(ch)
9
10# This is similar to main method
11if __name__ == '__main__':
12 keyboard = Keyboard()
13 keyboard.numKeys = 26
14 print(keyboard.numKeys)
15 keyboard.sendSignal('a')
Below is the same implementation in Javascript.
1class Keyboard {
2 constructor() {
3 this.numKeys = 0;
4 this.chars = [];
5 }
6 sendSignal(ch) {
7 console.log(ch);
8 }
9}
10
11var keyboard = Keyboard();
12keyboard.numKeys = 26;
13console.log(keyboard.numKeys);
14keyboard.sendSignal('a');