The final field cannot be assigned, for an interface
I have a class Product and an interface LargeProduct开发者_运维百科. Product implements LargeProduct.
LargeProduct has a variable height which has getter and setter methods which have to be implemented in the Product class.
The height variable in LargeProduct is defined like so:
public int height = null;
The getter method works fine:
public int getHeight() {
return height;
}
But the setter method does not:
public void setHeight(int height) {
this.height = height;
}
Errors:
The final field LargeProduct.height cannot be assigned
The static field LargeProduct.height should be accessed in a static way
I'm not sure which error it's actually giving.. I'm using Eclipse and when I hover it gives the first error, and at the bottom of the window it gives the second error.
Interfaces can only include constants, not general-purpose variables. Interfaces should only contain constants if they're genuinely relevant to the rest of the interface, and they should use SHOUTY_CASE
as per any other constant. It sounds like LargeProduct
shouldn't have a constant called height
- but instead, your implementation should declare the height
field.
Note that interfaces are meant to be APIs, showing the abilities of types. Fields shouldn't be part of the API - they're an implementation detail. After all, who's to say that you'll write getHeight
and setHeight
based on a simple variable? Those methods could query a database, or delegate to an instance of some other type. The consumer of the interface shouldn't know or care about that.
For further information about fields in interfaces, I suggest you read 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.
By default fields (member variable) in interface are public static final
and you don't have setter for final
The height variable in LargeProduct is defined like so:
public int height = null;
Variables defined in interfaces are implicitly static
and final
, i.e. constants. That's what the compiler complains about.
You cannot define an instance variable in an interface. Just leave it out - the get and set methods ensure that the classes can be used as intended. The actual variable is an implementation detail if the implementing classes.
You can't assign a value to a final field. Declare height in Product as
private int height;
Exactly org.life.java! And you cannot modify a static final variable! Because it's the way to determine a constant in Java.
精彩评论