encapsulation

encapsulation

  • Encapsulation is telling details and hiding them from the outside world.

Encapsulation in Java:

  1. Method is encapsulation.
  2. 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

  1. The constructor name must be exactly the same as the class name, even in case.
  2. Constructors do not write return value types, not even void.
  3. The constructor cannot return a concrete return value.
  4. If no constructors are written, the compilation will give away a constructor by default, with no arguments, no method body, and nothing to do.
  5. Once at least one constructor has been written, the compiler stops giving away.
  6. Constructors can also be overloaded. Overload: Same method name, different argument list.

A standard class usually has four components:

  1. All member variables need to be decorated with the private keyword.
  2. Write a pair of Getter/Setter methods for each member variable.
  3. Write a parameterless constructor.
  4. Write an all-parameter constructor.