class

Initializing final fields

With this example we are going to demonstrate how to initialize final fields of a class. In short, to initialize final fields of a class we have followed the below steps:

  • We have created class P, that has a private int attribute and overrides the toString() method of Object to return the String representation of the int value.
  • We have also created a class, BlankFinal, that consists of two private final int values, x initialized to 0 and y, and a final P.
  • It has a constructor where it initializes y and P, and another constructor where it uses an int x and initializes y and P using it.
  • We create a new instance of BlankFinal using the first constructor and then another instance using the second constructor.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;

class P {

    private int i;

    P(int i) {

  this.i = i;
    }

    @Override
    public String toString() {

  return "[" + new Integer(this.i).toString() + "]";
    }
}

public class BlankFinal {

    private final int x = 0; // Initialized final
    private final int y; // Blank final
    private final P z; // Blank final reference

    // Blank finals MUST be initialized in the constructor:
    public BlankFinal() {

  y = 1; // Initialize blank final

  z = new P(1); // Initialize blank final reference

  System.out.println("Initializing BlankFinal : y = " + this.y + ", z = " + this.z);
    }

    public BlankFinal(int x) {

  y = x; // Initialize blank final

  z = new P(x); // Initialize blank final reference

  System.out.println("Initializing BlankFinal : y = " + this.y + ", z = " + this.z);

    }

    public static void main(String[] args) {

  new BlankFinal();

  new BlankFinal(47);
    }
}

Output:

Initializing BlankFinal : y = 1, z = [1]
Initializing BlankFinal : y = 47, z = [47]

  
This was an example of how to initialize final fields of a class in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button