Java – when the field vars is final, do you need a getter?

In Java, the Convention (for me) is to make your field variables private and use getters and / or setters to access them This allows you to set rules for changing variable values

But what if the variable is final? Example:

public class Test {

    public final int MY_INT;

    public Test(int myInt) {
        MY_INT = myInt;
    }

}

Will this be allowed? It is compiled and works properly, but is it considered good code?

Solution

This is compiled, but it is not considered good code

MY_ Int violates the naming convention: all uppercase names are used for static final variables, also known as "class constants" (see this and this, Google's Java Style Guide) In order to comply with the naming convention, it is best to rename it Myint

It is recommended that you provide a getter to hide the implementation details of the course Interfaces contain only methods, not fields If you let someone else refer to this field by name, you will lose the freedom to change the name or your internal expression in the future

But most importantly, subclasses cannot override fields, they can only override methods If you provide a getter instead of a domain, subclasses will be able to cover and implement different behaviors Therefore, it is best to provide a getter and prohibit direct access to the site itself

(thanks @ Sotirios delimanolis for the coding style guide link, thank you very much!)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>