如何使用';下一代&x27;java数据对象样式与接口?
我正在以以下风格编写大多数不可变数据对象,有时被描述为或“功能性”:如何使用';下一代&x27;java数据对象样式与接口?,java,interface,immutability,field,encapsulation,Java,Interface,Immutability,Field,Encapsulation,我正在以以下风格编写大多数不可变数据对象,有时被描述为或“功能性”: 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 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/新样式或私有/公共字段的讨论并不感兴趣。)我宁愿改用继承或委派
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);
}
}
是我遗漏了什么,还是“下一代”只是“不可变类型”?是的,这可能是公平的。好的,但可能有一些字段不应该由用户设置。例如,
树
中的字段高度
。我想你会将“主类”中的构造函数设置为protected?我没有真正理解你。在哪个对象中有其他字段?假设我们有节点
,带有公共最终字段值
和高度
。我们还有两个子类Branch
和Leaf
。在分支的构造函数中
高度
是从其子级计算的,而在叶的构造函数中
则设置为0
。我们显然不希望用户能够调用新节点(int-value,int-height)
。充其量,他们甚至不应该知道这件事。