Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Where to declare a variable??

 
Jennifer Bhamoo
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello - I'm new here, so please bear with me...
Trying to figure out the difference between declaring variables in the following areas:
  • "class-level" (instance/class variables)
  • within default constructor

  • I think it starts to really matter when I start extending the class, since a subclass will have it's own default constructor, so if I want particular variables to be accessible to all subclasses, then they need to be declared at the "class-level". Just need a little reassurance of this though.
     
    Bear Bibeault
    Author and ninkuma
    Marshal
    Pie
    Posts: 64830
    86
    IntelliJ IDE Java jQuery Mac Mac OS X
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Absolutely. Any variable that is declared in a method, including a constructor, is available only within the scope of that method. You can initialize the value of variables in a constructor (indeed, that's one of their primary purposes), but the variables must be declared as class or instance variables to be accessible to methods of the class or derived classes.
    hth,
    bear
     
    Jennifer Bhamoo
    Ranch Hand
    Posts: 47
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks a bunch for the reply (and so quick too!!)
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic