Sunday, February 14, 2016

Initialize a "final" variable in constructor

A constructor will be called each time an instance of the class is created. 

Thus, the above code means that the value of "bookName" will be re-initialized each time an instance is created. But because the variable is declared final (and static), you can only do this

First Portion:
package com.rizvi;

public class RizviPersonalLibrary {
private final static String bookName;

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

}

Output:
Book Name: Road Rush

Constructor block:
But, if you remove static, you are allowed to do this:
package com.rizvi;

public class RizviPersonalLibrary {

private final String bookName;

    public RizviPersonalLibrary() {
    bookName = "Road Rush";
    }

public static void main(String[] args) {

RizviPersonalLibrary rpl = new RizviPersonalLibrary();
System.out.println("Book Name: "+rpl.bookName);
}

}


Output:
Book Name: Road Rush

Instance initializer block:
package com.rizvi;

public class RizviPersonalLibrary {

private final String bookName;



{

bookName = "Road Run";
}

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

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. is it allowed to initialize those variable inside other function except constructor?

    ReplyDelete