Hang on. Here you have posted a different example from page 25 of the K&B book (SCJP 5.0). What version of the book has this code on page 25? Have you another version of the book with this code on page 25?
A simple explanation about "this" is that it refers to the currently executing object. Since the main method is static--meaning it belongs to the class and not to any instance of the class--it has no knowledge of "this" so you cannot use this.geti() inside main().
But even if you remove "this" and simply call the method geti(), since geti() is inherited anyway, it still will not compile. simply because geti() is not static and you cannot use non-static members in a static context.
So in order to compile and run the code, you have to make the method geti() static, which also follows that you have to make the variable i static as well.
The part about the code being in the K&B book, i'm not pretty sure about that..?
Hope this helps you.
[ September 03, 2006: Message edited by: bing marquez ] [ September 03, 2006: Message edited by: bing marquez ]
Joined: Aug 03, 2002
From what I read in the SCJP 5.0 version of K&B, the authors have made it very clear that this code would not compile, because of the reasons bing has pointed out. To paraphase K & B "Static methods cannot access instance members because there is no instance" (Unless the static method creates an instance and use a reference to access the members of that instance)
Or you can make an instance of either a or b inside main(), then you can use that instance to invoke geti()instead of making geti() and i static.
Although this will get the code to compile and run, it is considered a syntax trick. Try sticking to the other suggestion as it helps show you the important concept: Static methods cannot access non-static variables.
I can't find this code on page 25. Please tell us what page you found this code on.
Joined: Aug 03, 2002
The problem with your latter code example, Shang, is that by converting the instance members into class (static) members you have changed the whole meaning of the class a. Now i is shared by all instances and geti() cannot be overridden.
If class a has to retain its original meaning, then the only way to access the instance members is to access them via a reference to an instance of class a. That certainly is not a syntactical trick. Perhaps you are thinking of accessing a static member of a class through a reference to an instance?
Also in your latter code: the b.geti() would be better replaced by just geti() or a.geti() (Oh, why didn't Java enforce class names beginning with capital letters?) [ September 03, 2006: Message edited by: Barry Gaunt ]