Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Accessmodifiers

 
majohnad majohnad
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the below question how is the output is 0,
public class AQuestion
{
private int i = giveMeJ();
public int j = 10;
private int giveMeJ()
{
return j;
}
public static void main(String args[])
{
System.out.println((new AQuestion()).i);
}
}
 
Karthik Veeramani
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this question was already discussed here.
When i gets initialised 1st, though the variable j is recognised, its not yet been assigned to 10. So it has its default value 0.
Others please correct me if im wrong.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's correct. Instance variable initializers are invoked in textual order, which means that i will be initialized prior to j. Therefore i ends up being initialized to 0 because j hasn't been initialized yet when i is assigned the value of j. By default, all instance variables have the value 0 (numbers, at least) when they are created.
The use of a method to set the value of i is just a ploy to trick the compiler because, had you used this:

The compiler would complain at you because it's smart enough to realize that you haven't yet initialized j and this is considered a "forward reference."
By putting the method invocation in there, you can trick the compiler into compiling what really boils down to the same code.
I hope that helps,
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic