0

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?

Farrukh Chishti
  • 7,652
  • 10
  • 36
  • 60

3 Answers3

0

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.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
0

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.
Community
  • 1
  • 1
Azodious
  • 13,752
  • 1
  • 36
  • 71
0

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.

trylimits
  • 2,575
  • 1
  • 22
  • 32