• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Instance Initializer

 
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,
Please have a look at the code as follows:
code1:
class Forwardreference {
double x = i;
static int i = 5;
int j;
j = j + 1;
double y = z;
static double z = - 1.2345;
}
If I compile the class there are compiler errors in line 5: j = j + 1
If I replace line 5 with code {j = j + 1) the initialization of j works:
code2:
class Forwardreference {
double x = i;
static int i = 5;
int j;
{j = j + 1;}
double y = z;
static double z = - 1.2345;
}
This code works. I heard the code {j = j + 1;} is an instance initializer. When is an instance initializer processed in the initialisation sequence and why does code1 not work and code2 work?
Thanks for your answers.
Thomas.
 
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy!
An instance initializer is processed JUST BEFORE the constructor, as you create an instance of a class.
So doing

is roughly equivalent with

The instance initializer is mostly used in anonymous classes, where you can't have constructors (since the anonymous class does not have a name). There the instance initializer is the only way to pre-initialize instance members.
Hope this helps!
/Kaspar
 
Would you turn that thing down? I'm controlling a mind here! Look ... look at the tiny ad ...
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic