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