encapsulation
encapsulation
- Encapsulation is telling details and hiding them from the outside world.
Encapsulation in Java:
- Method is encapsulation.
- The keyword private is also an encapsulation.
The keyword private
- Once decorated with private, it is still accessible from within the class, but not directly outside the scope of the class.
- To access a private member variable indirectly is to define a pair of Getter/Setter methods.
- It must be called setXxx or getXxx.
- Naming rules: For getters, there are no arguments. The return value type corresponds to the member variable. For setters, there is no return value, the parameter type corresponds to the member variable.
- For Boolean values of primitive types, Getter methods must be written as isXxx, and the setXxx rule remains unchanged.
Variable name duplication
-
When a local variable of a method has the same name as a member variable of a class, the local variable is preferred according to the “nearest principle”. If you need to access a member variable in Ben Thunder, use the following format:
This. Member variable nameCopy the code
-
By which method is called, that’s this.
A constructor
-
Constructors are methods that are specifically used to create objects, and when we create objects with the keyword new, we are actually calling the constructor.
-
Format:
Public Class name (parameter type parameter name) {method body; }Copy the code
Matters needing attention
- The constructor name must be exactly the same as the class name, even in case.
- Constructors do not write return value types, not even void.
- The constructor cannot return a concrete return value.
- If no constructors are written, the compilation will give away a constructor by default, with no arguments, no method body, and nothing to do.
- Once at least one constructor has been written, the compiler stops giving away.
- Constructors can also be overloaded. Overload: Same method name, different argument list.
A standard class usually has four components:
- All member variables need to be decorated with the private keyword.
- Write a pair of Getter/Setter methods for each member variable.
- Write a parameterless constructor.
- Write an all-parameter constructor.