• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B Study Guide - Chapter 5 pages 258 - 259

 
Brian Brumpton
Ranch Hand
Posts: 40
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, I'm missing a key concept here...

When I code the following example into code:

It won't compile...but


Compiles without issue.

What am I missing here. Something is not clicking in my brain as to why I have to put the declarations and assignments inside the main method.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brian Brumpton wrote:What am I missing here. Something is not clicking in my brain as to why I have to put the declarations and assignments inside the main method.

When you are inside a class body (and not in a method) you can declare (and initialize) variables. These variables can have both access (private, protected, public) and non-access (final, static) modifiers. All these staements will compile:If you don't mention an access modifier (as with var2), the variable has default access level. var3 is marked as static, so this variable is a class variable (meaning: regardless of how many instances are created of MyClass there will be just 1 var3 which is common to all MyClass objects/instances. The 3 other variables (var1, var2 and var4) are instance variables (or data member or instance member or...). Each MyClass object has its own values for these variables.

Now if you want to initialize an instance variable on a seperate line (or assign another value or you need a few lines to calculate the appropriate value), you can't do it in the class body itself, you need a constructor and/or an initializer block (for instance variables). For class variables, you can only use a static initializer block. Another code example:

When inside a method body, you don't have these kind of limitations. You can simply declare and initialize variables (as you already discovered). These variables are known as local variables, because their scope is limited to the method (unless they are e.g. used as a return value). So you can't use access modifiers when declaring such a variable. And the one and only non-access modifier you can use is final.

Hope it helps!
Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic