Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Blank Final Variables

 
Swati Singhal
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I read somewhere that a Blank Final Variable should be assigned a value before the end og a constructor.
Can somebody please throw some light on this?
Thanks
 
Thomas De Vos
stable boy
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A "Blank" final variable has to be initialized before it is used, be it in the constructor or somewhere else in the code.
Remember once your final variables have been initialized you cannot re-assign a value to it.
Practical: I recommend initializing any final variable where it is declared, no confusion.
[ March 22, 2004: Message edited by: Thomas De Vos ]
 
Gian Franco
blacksmith
Ranch Hand
Posts: 979
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Originally posted by Thomas De Vos:
A "Blank" final variable has to be initialized before it is used, be it in the constructor or somewhere else in the code.

I think blank final variables have always to be initialized, even if they are not used. They are implicitly initialized but an assignment before the end of the constructor is required (see the code below)

class A {
A(){foo();}
void foo(){}}
public class B extends A {
final int i;
B(){i=10;
}
void foo(){
System.out.println("i: " + i
);
}
public static void main(String [] args) {
B t = new B();
t.foo();
}
}

Greetings,
Gian Franco
[ March 22, 2004: Message edited by: Gian Franco Casula ]
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Swati
Maybe this thread will help you.
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For people eager to learn more about final fields, you can check out Chapter 2 - The Final Story of O'Reilly's new book "Hardcore Java"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic