3 minutes to take you to understand packaging

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

640?wx_fmt=png&wxfrom=5&wx_lazy=1


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/>

640?wx_fmt=png&wxfrom=5&wx_lazy=1


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

640?wx_fmt=jpeg

"Follow technology stalks and share interesting programming knowledge"



Guess you like

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