/*封装性:在类中定义public方法来访问私有属性*/
class Person4{
private String name = "张三";
private int age;
public void talk(){
System.out.println("名字是:"+name+",年龄为"+age);
}
public void setAge(int age){ //通过set方法修改私有属性
if(age>0){ //修改私有属性时可以加入判断语句
this.age = age;
}
else System.out.println("输入的年龄有误!");
}
public int getAge(){ //通过get方法得到私有属性
return this.age;
}
public int printName(){ //通过定义public方法获得私有属性
return this.age;
}
}
public class PersonDemo4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person4 per1 = new Person4();
per1.setAge(23); //修改私有属性的值
int a = per1.getAge();
System.out.println("通过get方法获得私有属性age的值:"+a);
System.out.println("通过定义公共方法获得私有属性age的值:"+per1.printName());
}
}
class Person4{
private String name = "张三";
private int age;
public void talk(){
System.out.println("名字是:"+name+",年龄为"+age);
}
public void setAge(int age){ //通过set方法修改私有属性
if(age>0){ //修改私有属性时可以加入判断语句
this.age = age;
}
else System.out.println("输入的年龄有误!");
}
public int getAge(){ //通过get方法得到私有属性
return this.age;
}
public int printName(){ //通过定义public方法获得私有属性
return this.age;
}
}
public class PersonDemo4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person4 per1 = new Person4();
per1.setAge(23); //修改私有属性的值
int a = per1.getAge();
System.out.println("通过get方法获得私有属性age的值:"+a);
System.out.println("通过定义公共方法获得私有属性age的值:"+per1.printName());
}
}