Java Foundation 04 Encapsulation and Interface

Click on " Java Head " above and select "Public Account"

Dry goods articles are delivered as soon as possible!


To summarize the previous content, an object refers to something, and a class refers to the type of an object. Objects can have state and actions, i.e. data members and methods.


Until now, data members and methods have been exposed both internally and externally. Inside the object, we use this to call the object's data members and methods. Outside the object, such as when we call the object in another class, we can use object.datamembers and object.methods () to call the data members and methods of the object.


We are going to encapsulate (encapsulation) the members of the object (members include data members and methods), thus allowing only part of the members to be called from the outside . With encapsulation, we can improve the usability and security of objects.


Packaging and Interface



Encapsulation is a common term for computers that preserves a limited external interface and hides specific implementation details. For example, in the Linux architecture , you can see that the Linux operating system encapsulates the specific details of the underlying hardware, and only retains the system call interface. The user is outside the package and can only perform the required operations through the interface.

 

Encapsulation is very common in life. For example, here is a rechargeable torch:


640?wxfrom=5&wx_lazy=1


Even without reading the manual, a user can guess the operation of this torch: switching and charging. This flashlight uses a plastic case to hide internal details that the user does not need to touch, leaving only two ports, the switch and the electrical plug. Using these two interfaces, the user is sufficient to use the function that the product wants to achieve in the design. If all the details are exposed to the user at the same time, the user will feel overwhelmed by the product (such as the unpacked remote control below). Thus, packaging improves the ease of use of the product .


640

 

If the product is not packaged, many details of the torch or remote control are exposed to the user: batteries, circuits, sealing rubber, etc. Although this allows the user to operate the product more freely, such as directly discharging the battery, taking out an LED light, and so on. However, users often bear a greater risk of damaging the product. Therefore, packaging improves the safety of the product .

 

A Java software product is the same as an everyday product. An object can have many members (data members and methods) inside it. There are some data members and methods that are only used internally. At this time, we will want to have a mechanism to "pack" the object, thereby encapsulating the object. In this way, users can easily learn and use the external interface without touching the internal members.


object member encapsulation



Java controls the external visibility of an object's members through three keywords : public , private , protected .


  • public: The member is externally visible, that is, the member is part of the interface

  • private: This member is not visible to the outside, it can only be used internally and cannot be accessed from the outside.


(protected involves the concept of inheritance, which will be discussed later)

 

Let's first encapsulate the previously defined Human class:


public class Test
{
   public static void main(String[] args)
   
{
       Human aPerson = new Human(160);
       System.out.println(aPerson.getHeight());
       aPerson.growHeight(170);
       System.out.println(aPerson.getHeight());
       aPerson.repeatBreath(100);
   }

}

class Human
{
   /**
    * constructor
    */

   public Human(int h)
   
{
       this.height = h;
       System.out.println("I'm born");
   }

   /**
    * accessor
    */

   public int getHeight()
   
{
      return this.height;
   }

   /**
    * mutator
    */

   public void growHeight(int h)
   
{
       this.height = this.height + h;
   }

    /**
     * encapsulated, for internal use
     */

   private void breath()
   
{
       System.out.println("hu...hu...");
   }


  /**
   * call breath()
   */

   public void repeatBreath(int rep)
   
{
       int i;
       for(i = 0; i < rep; i++) {
           this.breath();
       }
   }

   private int height; // encapsulated, for internal use
}


Internal methods are not affected by encapsulation. Human's internal methods can call any member, even height and breath() that are set to private


External methods can only call public members. When we are outside Human, such as in Test, we can only call members specified as public in Human, but cannot call members specified as private.


Through encapsulation, the Human class only retains the following methods as interfaces:


  • getHeight()

  • growHeight()

  • repBreath()

 

We can represent the Human class and its interfaces as follows:

640

"Remote with Shell"

 

If we forcibly call height from main:

System.out.println(aPerson.height);

The following error message will appear:

Test.java:6: height has private access in Human
        System.out.println(aPerson.height);
                                  ^
1 error

Beep, you're electrocuted! A member declared as private cannot be called externally.


In Java's usual specification, data members that express state (such as height) are set to private . Modifications to data members are performed through methods provided by the interface (such as getHeight() and growHeight()). This specification acts to protect data. The user cannot directly modify the data, and must read and write the data through corresponding methods. Class designers can add data usage specifications to interface methods.


class encapsulation



In a .java file, there can only be one class with the public keyword, such as the Test class above. So, from any other class, we can call this class directly. The Human class has no keywords. Earlier, the members of our objects also had no keywords. This absence of keywords also represents a kind of visibility, which I'll dig into in the package.

 

Exercise Encapsulate a Torch class to represent a torch. The interface has switch and charging. Internal members have electricity.


Summarize



package, interface

private, public


  • Original: cnblogs.com/vamei/archive/2013/03/27/2982209.html

640?

Head of Java

Daily sharing of Java dry goods

WeChat ID: javatuanzhang

640?

Long press to identify the QR code

Guess you like

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