File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes initialisation / declaration of variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "initialisation / declaration of variable" Watch "initialisation / declaration of variable" New topic

initialisation / declaration of variable

Gaelle Berton

Joined: Mar 24, 2011
Posts: 6
i stumbled across this in the practice exam book of Sierre Bates

the code compiles:

Shouldnt the "size" variable be declared before the constructor uses it? why doesnt it matter?
shuba gopal
Ranch Hand

Joined: May 12, 2011
Posts: 76
Hi Gaelle, is size declared before the Wheel constructor is invoked? In that case it shouldnt be a problem you agree? Can you please post the entire program for my understanding. Is it from K & B SCJP 6?
Gaelle Berton

Joined: Mar 24, 2011
Posts: 6
yes it is this same exam practice book:


shuba gopal
Ranch Hand

Joined: May 12, 2011
Posts: 76
Gaelle, I tried it

I am getting the following errors:

The declaration int size is missing in Bicycle. Where does it occur?
I looked thru the pdf version of the book but was not able to find this problem. Can you tell me the chapter/page number. thanks
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Shuba, your definition of the "Wheel" class is just missing the declaration of "size" which appears at the bottom of the class, as shown in the first post above; that's the whole point of this thread. All the other stuff you've posted, including your initial request for more code, is just a distraction and is not relevant, so let's just try to stick to the actual question, shall we?

Gaelle, the fact is simply that when the code inside a method or constructor body is compiled, all the members of that class are in scope. They don't need to be forward declared; it's perfectly OK -- and rather common -- for a method to refer to a variable or method which is declared later on in the same class.

[Jess in Action][AskingGoodQuestions]
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46375
Are you sure it's s = size; rather than size = s;?
I agree. Here's the link:
subject: initialisation / declaration of variable
It's not a secret anymore!