This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
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.
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.
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
Joined: Dec 02, 2009
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.