• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

scope issues

 
saipraneeth nallapareddy
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20514
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Hunter
 
saipraneeth nallapareddy
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic