黑马程序员技术交流社区

标题: 关于面向对象的问题 [打印本页]

作者: 湛添友    时间: 2014-3-25 19:36
标题: 关于面向对象的问题
public class Eencapsulation{
    public static void main(String[] args){
person Z=new person();
Z.setAge(24);
    }

}
class person
{
private int age;
public void setAge(int a)
{
if(a>0&&a<150)
{
age=a;
speak();
}
else
System.out.println("非法年龄");
}
public int getAge()
{
return age;
}
void speak()
{
System.out.println(age);
}
}

刚学到这里
这个getAge()
怎么用啊?
作者: linweiwen    时间: 2014-3-25 19:46
楼主,你的程序是自己写的还是例子里面的程序?
怎么看着有点奇怪?

要用getAge()方法,就是“对象.方法”嘛,
像setAge()那样,但就是感觉你这个程序有点奇怪,我改了一下:

  1. public class Test{
  2.     public static void main(String[] args){
  3.         person Z=new person();
  4.         Z.setAge(24);
  5.         System.out.println("Z这个对象的年龄是:"+Z.getAge());
  6.     }

  7. }
  8. class person
  9. {
  10.         private int age;

  11.         public void setAge(int a)
  12.         {
  13.                 if(a>0&&a<=150){
  14.                 this.age = a;
  15.         }else{
  16.                 System.out.println("非法年龄");
  17.         }
  18.         }

  19.         public int getAge()
  20.         {
  21.                 return this.age;
  22.         }

  23. }
复制代码

作者: 小周务商    时间: 2014-3-25 19:57
代码最好写得规范些。不然人家看得好累啊。。。。
作者: leon_hm    时间: 2014-3-25 20:51
  1. public class TestMain {

  2.         public static void main(String[] args) {// 未实现
  3.                 person Z=new person();
  4.                 Z.setAge(24);
  5.                 System.out.println("age:"+Z.getAge());//就是这样调用 对象.方法
  6.         }
  7.        
  8. }

  9. class person
  10. {
  11.         private int age;
  12.         public void setAge(int a)
  13.         {
  14.                 if(a>0&&a<150)
  15.                 {
  16.                 age=a;
  17.                 speak();
  18.                 }
  19.                 else
  20.                 System.out.println("非法年龄");
  21.         }
  22.        
  23.         public int getAge()
  24.         {
  25.         return age;
  26.         }
  27.        
  28.         void speak()
  29.         {
  30.         System.out.println(age);
  31.         }
  32. }
复制代码



作者: 湛添友    时间: 2014-3-26 08:16
linweiwen 发表于 2014-3-25 19:46
楼主,你的程序是自己写的还是例子里面的程序?
怎么看着有点奇怪?


是教学视频,我懂了,谢谢,
作者: trhthyj    时间: 2014-3-26 09:15
因为你的age被私有了,对外要提供访问方法,要获取age就使用对象调用getAge()方法啊
作者: Mr.__ㄨīn    时间: 2014-3-26 17:21
类中的方法调用,创建一个对象 person Z=new person();,用Z.getAge()调用即可。
建议你把视频在看看。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2