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 thetoString()
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 andy
, and a finalP
. - It has a constructor where it initializes
y
andP
, and another constructor where it uses an intx
and initializesy
andP
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.