• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

initialisation / declaration of variable

 
Gaelle Berton
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
thanks
 
shuba gopal
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes it is this same exam practice book:

...
..


 
shuba gopal
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49796
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure it's s = size; rather than size = s;?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic