类中似有属性的访问方式
2016-04-04 18:32
323 查看
/*封装性:在类中定义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());
}
}
相关文章推荐
- 类中没有构造方法的三种情况
- 玩玩nmap
- 一站式学习Wireshark(七):Statistics统计工具功能详解与应用
- Uvalive6885(最短路)
- putchar()
- return用法
- LA 3266&HDU 1052 Tian Ji -- The Horse Racing(田忌赛马,贪心)
- linux 用户及组的管理
- OpenGL之坐标转换(好文-清晰版)
- 初识asynctask和handler
- 抽象类与接口之间的关系
- sizeof用法汇总
- LeetCode之5_Longest Palindromic Substring
- 九九乘法表
- 接口与抽象类典型应用例子
- string用法
- 如何使用s:iterator循环每4条数据换一次行的代码
- 4.2日学习记录
- 【Android开发经验】使用Ant批量打包Android应用全然指南
- C语言字符串处理函数