Checkstyle for class variable

The validation 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 the declaration of x as final, but declaring x as final will give an error when initializing it in the constructor. What is the catch?

0
source share
3 answers

Bad style to make private and static fields available for modifications via setter. You must do one of the following:

1) enter the x final field and delete the set method for it.

or

2) make the field x non-static (delete the static ), then its final not required.

0
source

however, declaring x as final will give an error when initializing it in the constructor

To initialize static fields, use a static block .

And why should it be final ... The reason is that

  • This is private static and cannot be accessed externally.
  • If final is not required then there is no need to do it static

So either remove static OR use final private static

Now, your other piece of code:

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

Questions:

  • Fields
  • static should NOT be accessible with this .
  • Use a static block to initialize static fields.
0
source

You cannot change the value of a static leaf field.

if you really need x to be static change your method to

 public static void setX(int newX){ [...] 

remember that static methods cannot use "this".

this should solve your problem.

0
source

All Articles