Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question on forward referencing.

 
neha kanwal
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone please let me understand how the result is comes out to be 0 in the following code.

1. How the output comes out to be 0.
2. If I replaces private int i = giveMeJ(); with private int i = j;, I get compilation error due to forward referencing but why not in the earlier case.




Thanks,
Neha
 
Sanjeev Kulkarni
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neha,

1)
When you invoke (new AQuestion()).i in your main() method, the result is the value of that 'i' gets initialized with inside the constructor, whose body looks like this:

public AQuestion()
{
i = giveMeJ();
j = 10;
}

So, when 'i' tries to get the value from giveMeJ(), 'j' shouldn't have been initialized to 10, rather it would have the 0, the default value for an 'int'. So, i = 0 and the same would be printed.

One Important Point is: The instance variables get initialized in the order
they're read. So, if it were:

private int j = 10;
private int i = giveMeJ();

Then, you would get output as 10.

2) Forward referencing occurs because you're trying to assign a variable to value of some other variable that doesn't exist at that point at all!

Cheers!
Sanjeev
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please search this forum for "giveMeJ". This question of forward or not forward referencing has been discussed before.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic