Package Hello2;
public class Person {
String name;
int age;
public void Book () {
System.out.println ("reading");
}
public void TV () {
System.out.println ("watch TV");
}
}
Encapsulation is used in order to limit the use of class attributes, such as the above age is not very large, which requires encapsulation to implement
Packaging
/span>
package Hello2;
public class Person {
private String name;// using the private modifier is a property privatization using the private modifier to privatize properties , private int age; After privatization, it can only be used inside the class, not externally,
Private int age; //Use the method to assign a value to the Name property, You can use external (. setName), and then restrict the use of
public void SetName (String n) {
name=n; in the method;
}
public void setage (int m) {// for external use, provide a public Getter/setter method for the property (the operation of the property is only" save "(set method) and" Fetch "(Get method), this method is to use" save "
if (m>0&&m<120)//
then add some control code
Age=m;
}
Public String GetName () {
return name;
}
public int getage () {//This method is "fetch", to have a return value
return age;
}
public void Book () {
System.out.println ("reading" );
}
public void TV () {
System.out.println ("watch TV");
}
}
Package Hello2;
public class Testperson {
public static void Main (string[] arges) {
Person P=new person ();
P.name= "AAA"; cannot be used after privatization
P.setname ("AAA");
P.setage (34);
String N=p.getname ();
int A=p.getage ();
System.out.println (n+ "\ t" +a);
}
}
Running Result: AAA 0
The Java Learning Package