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 scope issues Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "scope issues" Watch "scope issues" New topic

scope issues

saipraneeth nallapareddy
Ranch Hand

Joined: Dec 02, 2009
Posts: 159
i have come across a code from the scjp 1.6 by kathy & bates
a block of code showing static context

the error can be resolved by placing the static keyword before int.
the other code which also sticks to same issue(in my point of view) but compiles fine without showing an error what concept did i missed to the point in the following code.

here i feel that the year variable which is a instance variable should through an error when accessed in the method from the above code point of view, i know that i used this particular way writing the piece of code like declaring the instance variables and references in the class but i doubt what i am missing when comparing with the above two codes. can anyone please explain.

Rob Spoor

Joined: Oct 27, 2005
Posts: 20273

In the second example, the instance field is accessed from an instance method, and that instance method is called on (you won't believe this) an instance of the class. If you'd remove the "bd." from "bd.showYear()" you'd get a similar error.

How To Ask Questions How To Answer Questions
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

Year is an instance variable of a class, in this case "public class BirthDate". To use this instance variable you need to either create an instance of the class or access through a static context.

In your first example the keyword static lets you use the instance variable without creating an object.

And in your second example the line:

creates an object which has that instance variable year. So when you use the show year method you are just accessing the objects declared attribute named year.


"If the facts don't fit the theory, get new facts" --Albert Einstein
saipraneeth nallapareddy
Ranch Hand

Joined: Dec 02, 2009
Posts: 159
thank you rob & hunter your explanations are great for me get the point, because i have been looking at the problem only from one view but not sticking to the basic in the second one but still thank you, both made me to realize what i have missed.
I agree. Here's the link:
subject: scope issues
jQuery in Action, 3rd edition