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:
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);
}
}
Output:
Book Name: Road Rush
Link: http://stackoverflow.com/questions/5093744/initialize-a-static-final-field-in-the-constructor
Link: http://stackoverflow.com/questions/5093744/initialize-a-static-final-field-in-the-constructor
This comment has been removed by a blog administrator.
ReplyDeleteis it allowed to initialize those variable inside other function except constructor?
ReplyDelete