Sunday, February 14, 2016

What is blank final variable in Java? Give an example.

What is blank final variable in Java? Give an example.

Blank final variable in Java is a final variable which is not initialized while declaration, instead they are initialized on constructor. Java compiler will complain if blank final variable is not initialized during construction. If you have more than one constructor or overloaded constructor in your class then blank final variable must be initialized in all of them, failing to do so is a compile time error in Java. Alternatively you can use constructor chaining to call one constructor from other using this keyword, in order to delegate initialization of blank final variable in Java.

How to use blank final variable in Java with Example

Blank final variable is like any other final variable but must be initialized in constructor as shown in below example. If you don't initialize or forget to initialize blank final variable then compiler will complain about it by throwing compile time error. static and final variable are treated as compile time constant and there value is replaced during compile time only.

package com.rizvi;

public class RizviPersonalLibrary {

private final String bookName;

public RizviPersonalLibrary() {

this.bookName = "Road Rush";
}

public RizviPersonalLibrary(String nameOfBook) {

this.bookName = nameOfBook;
}
public static void main(String[] args) {
RizviPersonalLibrary rpl = new RizviPersonalLibrary();
System.out.println("Book Name: " + rpl.bookName);

RizviPersonalLibrary rplNew = new RizviPersonalLibrary("Love and Affection");

System.out.println("New Book Name: " + rplNew.bookName);
}
}

Output:
Book Name: Road Rush

New Book Name: Love and Affection

No comments:

Post a Comment