A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© jonn 高级黑马   /  2013-1-16 19:23  /  1505 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. interface Share
  2. {
  3.         public float getArea() throws AreaException;
  4. }
  5. class AreaException extends Exception
  6. {
  7.         protected AreaException(String msg){
  8.                 super(msg);
  9.         }
  10. }
  11. abstract class ShareAbstract
  12. {
  13.     private static final double PI=3.1415;
  14.         protected static double getPI(){
  15.                 return PI;
  16.         }
  17. }
  18. class Rec extends ShareAbstract implements Share
  19. {
  20.          private static int len;
  21.          private Rec(int len){
  22.             this.len=len;
  23.          }
  24.          private static Rec rec;
  25.          public static Rec getIntance(){
  26.                  return rec=new Rec(len);
  27.          }
  28.          public void setLen(int len){
  29.                  this.len=len;
  30.          }
  31.          public float getArea() throws AreaException{
  32.                  if(len<0){
  33.            throw new AreaException("圆的半径 r < 0");
  34.                  }
  35.        return (float)(ShareAbstract.getPI()*len*len);
  36.          }
  37. }
  38. class Square implements Share
  39. {
  40.          private int len;
  41.          protected Square(int len){
  42.                  this.setLen(len);
  43.          }
  44.          public void setLen(int len){
  45.                  this.len=len;
  46.          }
  47.          public int  getLen(){
  48.                  return this.len;
  49.          }
  50.          public float getArea() throws AreaException{
  51.          if(len<0){
  52.                          throw new AreaException("正方形的边长小于零");
  53.                  }
  54.                  return (float)(len*len);
  55.          }
  56. }
  57. class ShareDemo
  58. {
  59.           public static void doGet(Share share){
  60.                   try{
  61.                System.out.println(share.getArea());
  62.                   }catch(AreaException e){
  63.               System.out.println("e.getMessage()");
  64.                   }
  65.                 }

  66.         public static void main(String[] args)
  67.         {     
  68.                 Rec.getIntance().setLen(4);  //使用单例无法修改 Rec的属性 len, 求解决....
  69.                 doGet(Rec.getIntance());
  70.         }
  71. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
冯海霞 + 1

查看全部评分

4 个回复

正序浏览
李海鹏 发表于 2013-1-17 08:27
private static int len;
这是静态,没有赋初值可以通过,我觉得为了减少代码,直接改成public不就好了么 ...

这样做就是封装,达到外部无法访问的目的
回复 使用道具 举报
private static int len;
这是静态,没有赋初值可以通过,我觉得为了减少代码,直接改成public不就好了么
回复 使用道具 举报
呵呵,自己解决了才是最好。。
回复 使用道具 举报
没人答? 自己解决了额
修改部分代码
  private Rec(int len) {
            this.setLen(len);
         }

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马