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

forward refrerences

 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How is it that the following code prints 0?
Why doesn't it throw a compiler error, because of the forward reference to j?

public class AQuestion
{
private int i = giveMeJ();
private int j = 10;

private int giveMeJ()
{
return j;
}

public static void main(String args[])
{
System.out.println((new AQuestion()).i);
}
}
 
Ransika deSilva
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kedar,
I guess it is because the variable j is refered before it is getting initialized so that it returns the defualt value for the int data type, Hope it make sence.
 
Arunkumar Ayyavu
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Forward references apply only to the variables. It doesn't apply to the methods.

This restriction is done to avoid circular references. For e.g.,
int i = j;
int j = i;
This circular reference issue will not occur in Methods.

But you might ask about this:
private void m1() {m2();}
private void m2() {m1();}
In this example, the compiler doesn't know what the methods do.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you search this forum for "giveMeJ" you will see that this question has come up often. Here's Corey's Tipline Article on the topic.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic