我有一个类Product和一个接口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,当我将鼠标悬停时出现第一个错误,并在窗口底部出现第二个错误。
接口定义了调用者和被调用者之间的契约。方法和常量是该合同的一部分,而不是字段。 (如果它是你不需要getter或setter)如果你想要父母定义一个字段,使用一个抽象类。 – 2010-12-14 10:46:03