我有一个类产品和一个接口(interface) LargeProduct。产品实现 LargeProduct。
LargeProduct 具有可变高度,它具有必须在 Product 类中实现的 getter 和 setter 方法。
LargeProduct 中的高度变量定义如下:
public int height = null;
getter 方法工作正常:
public int getHeight() {
return height;
}
但是setter方法不会:
public void setHeight(int height) {
this.height = height;
}
错误:
The final field LargeProduct.height cannot be assigned
The static field LargeProduct.height should be accessed in a static way
我不确定它实际上给出了哪个错误。我正在使用 Eclipse,当我悬停它时它给出了第一个错误,而在窗口底部它给出了第二个错误。
最佳答案
接口(interface)只能包含常量,不能包含通用变量。接口(interface)应该仅包含与接口(interface)的其余部分真正相关的常量,并且它们应该按照任何其他常量使用SHOUTY_CASE
。听起来 LargeProduct
不应该 有一个名为 height
的常量 - 但您的实现应该声明 height
字段。
请注意,接口(interface)是 API,显示类型的能力。字段不应该是 API 的一部分 - 它们是实现的细节。毕竟,谁能保证您会根据一个简单的变量来编写 getHeight
和 setHeight
?这些方法可以查询数据库,或委托(delegate)给其他类型的实例。界面的使用者不应该知道或关心这一点。
有关接口(interface)中字段的更多信息,我建议您阅读 section 9.3 of the Java Language Specification :
Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.
关于java - 无法分配最终字段,用于接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4438228/