What is Encapsulation?
Encapsulation is the process of packaging the base functionality of a class and providing access to the features of the class through a collection of behaviors. This means that the inner workings of the class are hidden from other classes and cannot be directly accessed.
Encapsulation is the process of packaging the base functionality of a class and providing access to the features of the class through a collection of behaviors. This means that the inner workings of the class are hidden from other classes and cannot be directly accessed.
Objects are responsible for maintaining their own state & behavior.
Another way to refer to encapsulation is 'information hiding'.
Following the laws of encapsulation, when designing a class, it is important to define the visibility of the states and behaviors contained within the class. This is known as visibility.
Private
A variable/state, method that is declared as private is only visible to the class that contains the variable or method. For instance:
The above class (Player) contains 5 private states (implemented as variables). As these states are private, they can only be modified directly from within the Player class.
When a state is private, no other object can read or change the value, directly. Getter & setter behaviors must be provided to allow access to these states, where access is required.
Public
Variables/states, methods & classes that are declared as public are visible to all other classes. For instance:
The above method is the constructor of the Player class. As a constructor is the first method called in the instantiation (object creation) process, it is vital that this constructor has a visibility of public.
Also:
The above getter & setter behaviors also belong to the Player class. These behaviors allow access to the internal state called _name. As such, they both have a visibility of public.
