The Artima Developer Community
Sponsored Link

Java Answers Forum
forward reference rule

1 reply on 1 page. Most recent reply: May 12, 2005 10:52 PM by Matthias Neumair

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Nihar Ranjan Pattanaik

Posts: 10
Nickname: nihar
Registered: May, 2002

forward reference rule Posted: May 12, 2005 9:43 AM
Reply to this message Reply
Advertisement
How & why the forward reference rule for the examples given below behaves differently.What is the internal architecture which drives this rule.

The code below is not compiling as the instance variable is getting initialized after the assignment..

class VirtualCafe {
private int chairsCount = 4 * tablesCount;
private int tablesCount = 20;
//...
}

where as this code below compiles

class VirtualCafe {

private int chairsCount = initChairsCount();
private int tablesCount = 20;

private int initChairsCount() {
return tablesCount * 4;
}
//...
}

Reference : http://www.javaworld.com/javaworld/jw-03-1998/jw-03-initialization_p.html


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: forward reference rule Posted: May 12, 2005 10:52 PM
Reply to this message Reply
It has nothing to do with initializing the variables.

It's about visibility.
Normally a variable is only visible for the code that follows "under" the variable declaration.

Java makes one exception: class variables
They are visible for every method in the class.

I don't know exactly when class variables are initialized, but I presume it happens before the constructor is called, because they are avaiable there (could also be, that they are initialized inside the constructor, but before the super call).
But the initialization sequentially.

Therefore in your first example b does not yet exist.

In you second example the compiler first declares the 2 variables without executing the methode for chairsCount.
Then it executes the method for chairsCount, after that it sets the value for tableCount.
Try to print out the number of chairs inside initChairsCount().
You will see that it is 0, because tablesCount is still 0 at the time of execution.


Try the following: Instead of using int, use Integer. You will get a NullPointer Exception, because when the method gets executed, the variable inside does not have a value yet.

Flat View: This topic has 1 reply on 1 page
Topic: Post increment problem Previous Topic   Next Topic Topic: how can I read a excel file

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use