Abstraction
Abstraction
in OOP is similar to the abstract data types (ADTs) we discussed in an earlier lesson. With ADTs, we do not need to know how a data structure is implemented. We only know the specifications of how it should behave.

Abstraction is also a way to tell the user of the class how to use the class without letting them know how it is implemented internally. With abstraction, you can "hide" all the decisions and processing steps within your Keyboard
class.
Most programming languages have special keywords to utilize the concept of abstraction (e.g., public
and private
in Java). When designing a class, we can use these keywords to prevent anyone from calling certain functions from outside of the class. The outside user should never be able to know all the properties and methods of a class. They should only know the methods that are public
and needed for the usage of the class.
Let's improve our Shape
class by adding some abstractions to it. The end-user (inside the Main
class) can only call the methods that are needed to use a Shape
object.
1// Shape.js
2class Shape {
3 // To make a class thread-safe,
4 // It is recommended to make all properties of object private
5 // We will later inherit this class. protected is a keyword that allows inherited classes to access parent class properties.
6 maxWidth;
7 maxHeight;
8
9 getMaxWidth() {
10 return this.maxWidth;
11 }
12
13 getMaxHeight() {
14 return this.maxHeight;
15 }
16
17 setMaxWidth(maxWidth) {
18 this.maxWidth = maxWidth;
19 }
20
21 setMaxHeight(maxHeight) {
22 this.maxHeight = maxHeight;
23 }
24
25 getMaxArea() {
26 return this.maxWidth*this.maxHeight;
27 }
28}
29
30// Now another programmer will use the Shape's public methods
31
32const shape = new Shape();
33
34// Access public methods
35console.log(shape.getMaxHeight());
36console.log(shape.getMaxWidth());
37
38// Try to access private data -> Compilation error
39console.log(shape.maxWidth);
A method that returns a property of an object is known as a getter method. A method that sets a property value is known as a setter method. These are often used in Java to make properties private and accessible only through methods. You could also do some validation or calculation before returning a property if you are using a getter or setter. We will learn more about getters and setters in a later lesson.