In the previous article, Uncle Steg took you to understand the concept of classes and objects in Java, then in this article Uncle Steg will shout to understand a feature of object-oriented - encapsulation
Package:
1. The concept hides some information of the class inside the class, and does not allow external programs to directly access it, but realizes the operation and access to the hidden information through the methods provided by the class.
2. Benefits:
a. Data can only be accessed through specified methods
b. Hide the instance details of the class for easy modification and implementation
3. Implementation steps of encapsulation
3.1 Modify the visibility of the attribute (operation: set to private)
3.2 Create getter/setter methods (purpose: for reading and writing properties)
3.3 Add property control statements to getter/setter methods (purpose: to judge the validity of property values)
<code demo/>
access modifier
private role: this class
Default (default) role: same package
protected role: this class is the same as subclass
Public role: all (this class, the same package, subclasses, others)
this keyword
1. The this keyword represents the current object
this.properties operate on the properties of the current object
this. method calls the method of the current object
2. When encapsulating the properties of an object, the this keyword is often used
Tips: Use eclipse to automatically generate get() and set() methods:
Step 1: You can select Source from the right-click menu in eclipse
Step 2: Generate Gethers and Setters
Inner classes in Java
An inner class is a class defined inside another class. Correspondingly, a class containing an inner class is called an outer class.
The main role of the inner class:
1. The inner class provides better encapsulation, which can hide the inner inside the outer, and does not allow other classes in the same package to access the class
2. The methods of the inner class can directly access all the data of the outer class, including private data.
3. The functions implemented by the inner class can also be realized by using the outer class, but sometimes it is more convenient to use the inner class.
What are the inner classes?
- member inner class
- static inner class
- method inner class
- Anonymous inner class
Long press the QR code to follow
"Follow technology stalks and share interesting programming knowledge"