Package Penalty for java04; / * * Problem Description: When defining the age of Person, can not prevent unreasonable value set to come * Solution: Use the keyword will need to protect private member variables can be modified * * Once a private use has been modified, originally class which can still be freely accessible. * However, beyond the scope of this class will complement not directly access the * * Introduction to access private member variables, is the definition of a pair of children Getter / Setter method * * naming getXxx setXxx * * For getter, it can not have parameters, return value types and members corresponding to the type * for the setter, you can not have a return value, parameter types and the corresponding member variables * * * / public class the Person { String name; // name Private int Age; // Age // Private Age = int 12; // Age public voidShow () { System.out.println ( "My name:" + name + ", this year's" + age); } // This method members, set up specifically for the age data public void setAge ( int NUM) { IF (NUM <100 && NUM> 0 ) { Age = NUM; } the else { System.out.println ( "data unreasonable" );} // Age NUM =; } // this method members. Age data acquiring dedicated public int getAge () { return age; } }
Package java04; public class DemoPerson { public static void main (String [] args) { the Person Person = new new the Person (); person.show (); PERSON.NAME = "Bob" ; // person.age = -20; Error written person.setAge (10 ); System.out.println ( "get Age" + person.getAge ()); // get the age of 10 person.show (); // my name: Xiao Ming, this year 10 } }