Java Starts from scratch 13 (encapsulation)

Source: Internet
Author: User

I. What is encapsulation and why should it be encapsulated

For object-oriented: encapsulation is the wrapping of methods and properties into a program unit, and this unit is implemented in the form of classes.

Simply put: Closure is the privatization of properties, providing public methods to access private properties

The role of encapsulation:

    • Encapsulation reflects and the relative independence of things, the role of encapsulation in programming is: so that other parts of the object can not arbitrarily change the properties of the object, thereby effectively avoiding the impact of external error operations on this object
    • Improved loose coupling, code reusability

Loose coupling: think of the object as a battery, which can be used not only in the camera, but also in the remote control, hair dryer and shaving and so on, we say that the loose coupling of the battery is very good, and to achieve such a good loose coupling is the premise that the object has a good encapsulation

Second, the implementation of the package
    1. Property Privatization Private
    2. Set the Get/set method
    3. Set the necessary restrictions on attributes
 PackageCom.pb.demo3; Public classPerson {PrivateString name;//name    PrivateString sex;//Sex    Private intAge//Age//set getter and setter methods     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getsex () {returnsex; }     Public voidsetsex (String sex) {if(Sex.equals ("male") | | sex.equals ("female"))){            //setting a gender limit, an illegal value will prompt an error         This. Sex =sex; }Else{System.out.println ("Sex is not legal, sex can only be: male or female"); }    }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {        if(Age>0 && age<=150){            //set Age Limits         This. Age =Age ; }Else{System.out.println ("Age is only between 1-150 years old"); }    }     PublicPerson () {} PublicPerson (string name, String sex,intAge ) {         This. Name =name;  This. Sex =sex;  This. Age =Age ; }         Public voidsay () {System.out.println ("Self-Introduction:"); System.out.println ("Name:" + This. Name); System.out.println ("Gender:" + This. Sex); System.out.println ("Age:" + This. Age); }}

Test class:

 PackageCom.pb.demo3; Public classPersontest { Public Static voidMain (string[] args) { person person=NewPerson (); Person.setname ("Hanbing"); //Pass in an illegal valuePerson.setsex ("neutral"); //Pass in an illegal valuePerson.setage (200); //calling the normal method outputPerson.say (); }}

Result: Error will be prompted

Gender is not legal, sex can only be: male or female
Age is only between 1-150 years old
Self Introduction:
Name: hanbing
Gender: null
Age: 0

As can be seen from the result, the illegal value will be the initial value of the data type String null,int to 0

You can also initialize a value in a construction method so that when the value is set to be illegal, the initialized value is used

 Public Person () {        this. Name = "Anonymous";          this. Sex = "male";         this. Age =;    }

Re-executing the wrong value when passing in

 PackageCom.pb.demo3; Public classPersontest { Public Static voidMain (string[] args) { person person=NewPerson (); Person.setname ("Hanbing"); //Pass in an illegal valuePerson.setsex ("neutral"); //Pass in an illegal valuePerson.setage (200); //calling the normal method outputPerson.say (); }}

Results:

Gender is not legal, sex can only be: male or female
Age is only between 1-150 years old
Self Introduction:
Name: hanbing
Gender: Male
Age: 22

Java Starts from scratch 13 (encapsulation)

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.