Using final in java

I was wondering what is the difference between

public final type attribute_name;

      

and

private type attribute_name;
public type getA_name() {
  return attribute_name;
}

      

Basically, I want to make the attribute read-only, so it can't change after it's initialized.
Can I do this public final

or do it private

and make it only available through a getter (no setter)?

+3


source to share


7 replies


A MUSTfinal

field must be set before the constructor exits. Once installed, the link cannot be changed (the value cannot be reassigned). The emphasis on cannot be reassigned . This means that although the link cannot change, the value itself can change .

It is legal:

final List<Integer> list = new List<Integer>();
list.add(5); // the value of list changes, but the reference doesn't

      

Is not:

final List<Integer> list = new List<Integer>();
list = new List<Integer>(); // may seem sort of redundant but the compiler won't allow it nonetheless

      


A private

variable with a single getter can be reassigned inside the class holding it (but it is not externally visible, so it cannot be reassigned outside the class holding it). Also, outside of the class, the reference is not available, so the variable cannot be changed, except for the class holding it.

A final

variable cannot be reassigned anywhere, but if it is public, another class can still access the reference and change the value of whatever object it points to.

If you do not want the variable to be reassigned after initialization, as you described, using both final

, and so private

.


Use final

for something like this:

public class User {

    private final long registrationTimeMillis;

    public User(/* various parameters probably would be here */) {
        registrationTimeMillis = System.currentTimeMillis();
    }

    public long getRegistrationTimeMillis() {
        return registrationTimeMillis;
    }
}

      

We do not expect the user registration time to change, so it makes sense to prevent it from changing after build.




Use private

without configuration for something like this:

public class VendingController() {

    private int drinksStocked = 0;
    private int drinksDispensed = 0;

    public void dispenseDrink() {
        drinksDispensed++;
    }

    public void stockDrinks(int numberOfDrinks) {
        drinksStocked = getDrinksRemaining() + numberOfDrinks;
        drinksDispensed = 0;
    }

    public int getDrinksRemaining() {
        return drinksStocked - drinksDispensed;
    }
}

      

We don't want to change the value drinksDispensed

, except when dispenseDrink()

or is called stockDrinks(int numberOfDrinks)

. It still needs to be reassigned by its own class when the vending machine is refilled, so we shouldn't be doing itfinal


In terms of usage public final

, it is generally in Java that only happens for constants and that keyword is static

also included since constants should not be instance dependent.

An example of when it makes sense to use public static final

public class UnitConversions {

    public static final double CENTIMETERS_PER_INCH = 2.54;

}

      

It can then be used in a method like this:

public double convertFromCentimetersToInches(double centimeters) {
    return centimeters / UnitConversions.CENTIMETERS_PER_INCH;
}

      


Good luck and happy coding.

More reading in final fields

+1


source


If it is not final

, but private

, the class itself may change the value.



+4


source


The last modifier allows you to assign a field only once - after that it cannot be changed and must be set during object construction (that is, before the constructor returns).

If you want to make a field read-only, use the principles of hiding information: make it private and provide a public getter that returns the field (or a copy for non-primitive types).

You should public final

only use for true constants. Even if your field is unchanged due final

, it is often recommended to do it private

.

+1


source


It depends on several factors.

If it is a real constant that is known before and will never change, use final

. In Java, final

fields can also be initialized in the constructor, so if your value is known at build time, you can also use final

.

If this value will be set (once, multiple times) at runtime, use private

+ getter

.

+1


source


The correct way is to think ahead. What will help you achieve your goals? You may also want to assign a value to this variable later on. If I were you, I would do it with the creatin get method and keep the variable private.

Full documentation for the keyword final

: http://en.wikipedia.org/wiki/Final_(Java)

0


source


Depends on what you want to access. Public variables can be accessed from any project class and package, where private variables can only be accessed from the class in which the variable resides.

The "final" statement makes it permanent and read-only.

0


source


Lets assume that type

is an object reference and not a primitive type.

  • public final type attribute_name

    means it attribute_name

    cannot be reassigned to refer to something else. But it attribute_name

    can be used to call a method that changes its state.

  • In private type attribute_name

    only methods within a class can call methods on attribute_name

    .

So, if you want it to remain constant, use approach (2). Limit methods to public

those that end up calling methods on attribute_name

that don't change its state.

0


source







All Articles