Experience the encapsulation of Java

Source: Internet
Author: User

1  PackageCom.cnblogs.java;2 //experience the encapsulation of Java3 /*4 * The following human age assignment-300 years old, obviously unreasonable, this directly to the Class property assignment, sometimes although unreasonable but will compile through. 5 * So we consider not letting the object manipulate properties directly, but using the object invocation method to assign a value to the property, and in the method we can further restrict6 * The size of the assignment problem. 7 * Workaround: Privatize the properties of the class and invoke the properties of the modified class through a common method. (Limit modified values in a method)8  */9  Public classTestperson {Ten      Public Static voidMain (string[] args) { OnePerson p=NewPerson (); A //p.name= "Master Kang"; - //p.age=-300; -P.setname ("Xiao Ming"); theP.setage (12); -         //this kind of compilation through but unreasonable assignment method to avoid -          - p.info (); +     } - } + classperson{ A     PrivateString name;//privatize properties to avoid direct invocation of properties by an object.  at     Private intAge ; -      Public voidinfo () { -System.out.println ("The name of the person is:" +name+ "Age is:" +Age ); -     } -      PublicString GetName () {//Get a name -         returnname; in     } -      Public intGetage () {//Get Age to         returnAge ; +     } -      Public voidSetName (String N) { the         if(N.length () >0 && n.length () <8){ *Name=N; $}Else{Panax NotoginsengSystem.out.println ("Please enter a short name!") "); -         } the     } +      Public voidSetage (inta) { A         if(A>0 && a<130){ theAge=A; +}Else{ -System.out.println ("This is not the age a man can reach!") "); $         } $     } -}

Operation Result:

The person's name is: Xiaoming Age is: 12

Experience the encapsulation of Java

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.