package hello2;
public class Person {
String name;
int age;
public void book(){
System.out.println("看書");
}
public void tv(){
System.out.println("看電視");
}
}spa
使用封裝是爲了在類屬性使用時一些限制,好比上面年齡不可能很大,這就須要封裝來實現get
封裝class
package hello2;
public class Person {
private String name;// 使用private修飾符是屬性私有化使用private修飾符使屬性私有化, private int age;私有化以後只能在類內部使用,不能外部使用,
private int age; //使用方法給name屬性賦值,就能夠外部使用(.setName),而後在方法中限制使用
public void setName(String n){
name=n;
}
public void setAge(int m){//要想外部使用,給屬性提供公有的getter/setter方法(對屬性的操做只有「存」(set方法)和「取」(get方法)),此方法是用「存」
if(m>0&&m<120)//方法
public String getName(){
return name;
}
public int getAge(){//此方法是「取」,要有返回值
return age;
}
public void book(){
System.out.println("看書");
}
public void tv(){
System.out.println("看電視");
}
}
package hello2;
public class TestPerson {
public static void main(String[] arges){
Person p=new Person();
//p.name="AAA";使用私有化後不能使用
p.setName("aaa");
p.setAge(34);
String n=p.getName();
int a=p.getAge();
System.out.println(n+"\t"+a);
}
}static
運行結果:aaa 0new