【发布时间】:2012-04-28 19:52:52
【问题描述】:
我的大部分不可变数据对象都采用以下风格编写,有时被描述为'next generation' 或“功能性”:
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 或私有/公共字段的讨论并不感兴趣。)
【问题讨论】:
-
是我遗漏了什么,还是“下一代”只是“不可变类型”?
-
是的,可以这么说。
标签: java interface immutability field encapsulation