Checkstyle on class variable

旧街凉风 提交于 2019-12-12 03:35:31

问题


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

  1. It is private static and can't be accessed from outside.
  2. If it is not required to be final then no need to make it static

So, either remove static OR use final private static

Now, your other part of code:

public void set(int x) {
    this.x = x;
}

Issues:

  1. static fields should NOT be accessed using this.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!