in Java it's convention (as far as I am concerned) to keep your field variables private and access them using getters and/or setters. This is so that you can set rules for changing the values of the variables.
But what if the variables are final? Example:
public class Test {
public final int MY_INT;
public Test(int myInt) {
MY_INT = myInt;
}
}
Would this be allowed? It is compiled and works fine, but is it considered good code?
This compiles but it's not considered good code.
MY_INT
violates the naming convention: names with all caps are used for static final
variables, also known as "class constants" (see this and this, Google's Java style guide too). to conform to naming conventions, it would be better to rename to myInt
.
It's recommended to provide a getter to hide implementation details of your class. Interfaces contain only methods, not fields. If you let other classes refer to this field by name, then you lose the freedom to change the name or your internal representation later.
But most importantly, sub-classes cannot override fields, they can only override methods. If you provide a getter instead of a field, sub-classes will be able to override that and implement different behavior. So it would be better to provide a getter and forbid direct access to the field itself.
(Thanks to @Sotirios Delimanolis for the coding style guide links, much appreciated!)