我在寫我的大部分不可改變的數據對象在下面的風格,這是somtimes或描述爲'next generation'「功能」:如何將「下一代」java數據對象樣式與接口一起使用?
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 /新型或私有/公共領域的討論很感興趣。)
我錯過了什麼,或者是「下一代」簡單的「不可變類型」嗎? – 2012-04-28 20:03:16
是的,這可能是公平的說法。 – 2012-04-28 20:29:45