0

我正在以以下风格编写我的大部分不可变数据对象,有时将其描述为“下一代”或“功能性”:

public class Point {
   public final int x;
   public final int y;

   public Point(int x, int y) {
      this.x = x;
      this.y = y;
   }
}

我想对接口指定的数据对象使用相同的样式:

public interface Point {
   public final int x;
   public final int y;
}

public class MyPoint {
   public MyPoint(int x, int y) {
      this.x = x;
      this.y = y;
   }
}

public class Origin {
   public Origin() {
      this.x = 0;
      this.y = 0;
   }
}

但这在 java 中是不允许的,它在接口代码和实现中都会出错。

我可以将我的代码更改为

public interface Point {
   public int x();
   public int y();
}

public class MyPoint {
   private int mx, my;
   pulic MyPoint(int x, int y) {
      mx = x;
      my = y;
   }
   public int x() {return mx;}
   public int y() {return my;}
}

public class Origin {
   public int x() {return 0;}
   public int y() {return 0;}
}

但它是更多的代码,我不认为它在 API 中给人几乎相同的简单感觉。

你能看出我的困境的出路吗?还是您个人使用第三种甚至更简单的样式?

(我对可变/不可变、getterSetter/new-style 或私有/公共字段的讨论并不感兴趣。)

4

1 回答 1

1

我宁愿改用继承或委托

public class Point {
 public final int x;
 public final int y;

 public Point(int x, int y) {
   this.x = x;
   this.y = y;
 }
}

遗产

public class MyPoint extends Point {
   public MyPoint (int x, int y) {
     super (x, y);
   }
   ....
}

public class Origin extends Point {
   public Origin () {
     super (0, 0);
   }
}
于 2012-04-28T20:04:53.870 回答