[Java Getting Started note] Object-oriented three major features: encapsulation

Source: Internet
Author: User
Tags control characters modifiers

Learn about encapsulation what is encapsulation?

In Java's object-oriented programming, there are three basic features: encapsulation, inheritance, and polymorphism. First, let's take a look at the package:

In Java's object-oriented programming, encapsulation (encapsulation) refers to a method of wrapping and hiding functions as part of detail. Encapsulation can be considered a protective barrier against the code and data of the class being arbitrarily accessed by the code defined by the external class. If you want to access code and data in a class, you must pass strict control.

Why use encapsulation?

Using encapsulation primarily has the following benefits:

    • Ability to hide implementation details for some of the features in the class. Allow callers to access the functionality and data of the class in advance and to restrict unreasonable access to the data in the class.
    • Checking the data is helpful to protect the integrity and rationality of the object information.
    • Easy to modify and maintain the code, improve the maintainability of the code.
How do I use encapsulation? Access Rights control

In Java, there are four access control characters that encapsulate the data of classes and objects:

Modifier Class Internal Same package Sub-class really Global scope
Private
Default
Protected
Public

Modifiers can also be used for external classes, although external classes can use both public and default modifiers.

Example
 Public classPerson {//decorated with private modifier, external unreachable    PrivateString name;//name    Private intAge//Age    PrivateString Idnum;//ID Number//get the name of the class object     PublicString GetName () {returnname; }        //sets the name of the object for the class and does not assign a value if a null value is passed in     Public voidsetName (String name) {if(name.length () = = 0 | | name = =NULL){            return; }         This. Name =name; }        //Get Age     Public intGetage () {returnAge ; }        //set the age to set the parameter to the object when the passed parameter is greater than or equal to 0 o'clock     Public voidSetage (intAge ) {        if(Age >= 0){             This. Age =Age ; }    }        //Get ID number     PublicString Getidnum () {returnIdnum; }        //set up a social security number     Public voidsetidnum (String idnum) { This. Idnum =Idnum; }  }

In the example above we have added the private modifier to the attributes in the class, the external can no longer directly access and modify these properties, if necessary, we need to add getxxx and Setxxx methods to access these things, while the We can also control access to these properties in these methods, such as the name cannot be empty, the age cannot be negative, and so on.

In this way we can see the integrity and rationality of the program reasonable control, but also better to enhance the security of the code, but also to better management and maintenance of code.

 Public class Test {    publicstaticvoid  main (string[] args) {        new Person ();         = "Zhang San";  // error, no direct access        P.setname ("Zhang San");        P.setage (-5);         System.out.println (P.getage ());   // output The default value of 0, although we passed a value in the previous line of code, but we have control in the Setage method, so the incoming negative number is not assigned to the P object     }}

Principles of Use

With regard to the use of access controls, we should try to conform to the following principles:

    • Most of the member variables of a class should use the private modifier, and only some static, global variable field, consider using the public modifier.
    • If a class is primarily used as a parent class for other classes, most of the methods and properties in the class want the quilt class to be rewritten and used without being called directly externally, you should use the protected modifier.
    • The public modifier should be used to expose methods that are exposed directly to external use.
    • The function of a method should use the private modifier only if it is called inside the class.

[Java Getting Started note] Object-oriented three major features: encapsulation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.