6. Encapsulation - ZolotovaNatalia/JavaCourse_2017 GitHub Wiki
Encapsulation
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. A feature of objects is that an object's methods can access and modify the fields that belong to the concrete object. For more information see here.
There are four OOP principles that describe how we should write our programs based on objects:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
In this lecture we talk about Encapsulation.
What is Encapsulation?
Encapsulation means hiding the implementation details of the class from the outside world, not letting to modify them. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. However if we setup public getter and setter methods to update(String setColor(String color)) and read (for e.g. String getColor()) the private data fields then the outside class can access those private data fields via public methods. That’s why encapsulation is known as data hiding. Lets go back to the example with Bus object from the previous lecture.
In the class Bus we created several fields, that are private:
private int id = 0;
private int maxAmountOfPassengers = 0;
private String brand = "";
private String color = "";
The keyword private, it's called access modifier, protects these fields from modification after object creation. We can use them only via public methods setters and getters that are visible from the outside:
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMaxAmountOfPassengers() {
return maxAmountOfPassengers;
}
public void setMaxAmountOfPassengers(int maxAmountOfPassengers) {
this.maxAmountOfPassengers = maxAmountOfPassengers;
}
...
If we want to keep these fields unmodifiable after the object creation, we need to define a constructor with arguments, that helps us to create object and initialize its fields simultaneously
public Bus(int id, int maxAmountOfPassengers, String brand, String color){
this.id = id;
this.maxAmountOfPassengers = maxAmountOfPassengers;
passengers = new Passenger[maxAmountOfPassengers];
this.brand = brand;
this.color = color;
}
We also should remove setters for these fields. Thus, we defined a class that is completely encapsulated: all details are hidden and no field modification is available.
Benefits of Encapsulation:
- The fields of a class can be made read-only or write-only.
- A class can have total control over what is stored in its fields. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.