One of the three cornerstones of object orientation - encapsulation

1. Three steps of packaging

1. Object property privatization (private)

2. Use setter and getter methods

3. to limit

2. Detailed explanation


1. Object property privatization (modified with private)

Of course, there are shortcut keys when using this method, as shown below

Right click on the stand-alone machine, stand-alone Source, there are Generate setters and getters... Click it, select all or part of it, check what you need, and confirm to proceed.


2. Use setter and getter methods

Of course, there are shortcut keys when using this method, as shown below

Right click on the stand-alone machine, stand-alone Source, there is Generate Constructor using Fields... Click it, select all or part of it, check the required ones, and confirm to proceed.


Of course, there are shortcut keys when using this method, as shown below



3. to limit

use a constructor to limit it


What is the construction method here?

1) Every class in Java has a constructor that initializes an object of that class

2) The constructor method name is the same as the class name, and there is no return type

3) The constructor can only be called by the new keyword and this(), this() can only be used in the constructor to call other constructors, and can only be used as the first statement of the constructor code body

4. Supplement: method overloading

Features: 1) The method names are the same

           2) The method name is the same

           3) The parameter list is different

The different parameter lists can be: different numbers, different orders, and different types.


The circled part is the parameter

In order to facilitate memory, it can be remembered as: same name with different parameters


3. A small encapsulated task, as follows (create Dog class)


Its code is as follows

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325645556&siteId=291194637