Java - final Reference Variables

Introduction

Both primitive and reference variables can be declared final.

The value stored in a final variable cannot be changed once it has been set.

A reference variable stores the reference of an object.

A final reference variable means that once it references an object (or null), it cannot be modified to reference another object.

Consider the following statement:

final Account act = new Account();

Now, you cannot make the act variable to reference another object in memory.

The following statement generates a compilation time error:

act = new Account(); // A compile-time error. Cannot change act

The following are valid statements, which modify the balance instance variable of the Account object:

act.deposit(2.00); // Modifies state of the Account object
act.debit(3.00);      // Modifies state of the Account object

Demo

class Account {
  private double balance;

  public double getBalance() {
    return this.balance;
  }/*from  w w  w .jav a  2s.  c  o m*/

  public void credit(double amount) {
    this.balance = this.balance + amount;
  }

  public void debit(double amount) {
    this.balance = this.balance - amount;
  }
}

public class Main {
  public static void main(String[] args) {
    final Account ac = new Account();
    double balance = ac.getBalance();
    System.out.println("Balance = " + balance);

    // Credit and debit some amount
    ac.credit(1.1);
    ac.debit(1.12);

    balance = ac.getBalance();
    System.out.println("Balance = " + balance);

    // Attempt to credit and debit invalid amounts
    ac.credit(-2.90);
    balance = ac.getBalance();
    System.out.println("Balance = " + balance);

    // Attempt to debit more than the balance
    ac.debit(3.00);

    balance = ac.getBalance();
    System.out.println("Balance = " + balance);
  }
}

Result

Related Topic