问题
Check style says that for a private class variable "must be declared final".
class Test {
private int x=1;
public void set(int x) {
this.x = x;
}
}
In the above case it calls to declare x as final however declaring x as final would give error on initializing it in the constructor. What's the catch?
回答1:
It is a bad style to make private
and static
field accessible for modifications through setter. You have to do one of the following things:
1) make field x
final
and remove set
method for it.
either
2) make field x
non-static (remove static
keyword), then it will be not required to make it final
.
回答2:
however declaring x as final would give error on initializing it in the constructor
To initialize static fields use static block.
And, why it should be final
... The reason is that
- It is
private static
and can't be accessed from outside. - If it is not required to be
final
then no need to make itstatic
So, either remove static
OR use final private static
Now, your other part of code:
public void set(int x) {
this.x = x;
}
Issues:
static
fields should NOT be accessed usingthis
.- Use static block to initialize static fields.
回答3:
you cannot change the value of a static final field.
if you really need x to be static, change your method to
public static void setX(int newX){
[...]
keep in mind, that in static methods "this" cannot be used.
this should solve your problem.
来源:https://stackoverflow.com/questions/15218226/checkstyle-on-class-variable