Public class variable fields do not respect the encapsulation principle and has three main disadvantages:
By using private attributes and accessor methods (set and get), unauthorized modifications are prevented.
public class MyClass {
public static final int SOME_CONSTANT = 0; // Compliant - constants are not checked
public String firstName; // Noncompliant
}
public class MyClass {
public static final int SOME_CONSTANT = 0; // Compliant - constants are not checked
private String firstName; // Compliant
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
Because they are not modifiable, this rule ignores public final fields.