permaculture playing cards
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes call to shadowed static method at runtime!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "call to shadowed static method at runtime!!!" Watch "call to shadowed static method at runtime!!!" New topic

call to shadowed static method at runtime!!!

Rishi Singh
Ranch Hand

Joined: Dec 09, 2000
Posts: 321
The output to the following programme is "Child.Test()" followed by Base.Test();. How come the call to the method baseObject.test() takes up the Base class test()method.Is it that it is static and the call to it is resolved at class loading time, though the baseO bject is of class Child???.please clarify
class Base
static void test() {
public class Child extends Base {
static void test() {
static public void main(String[] a) {
Child anObj = new Child();
Base baseObj = (Base)anObj;
Rajiv Ranjan
Ranch Hand

Joined: Sep 28, 2000
Posts: 61
Hi Rishi:
This is a special case applicable to staic methods.
Just remember a simple rule :
" The choice of the static method depends on the class of the reference variable that calls it"
Sivaram Ghorakavi
Ranch Hand

Joined: Nov 30, 2000
Posts: 56
The Static members belock to the class not to the instance. So in this case, static method overriding, when anObj.test() is called it refers to the method from the class reference that is Child. Saying that
Base baseObj = (Base)anObj;
baseObj.test(); would referer to the test()from class Base.
Hope this helps.
I agree. Here's the link:
subject: call to shadowed static method at runtime!!!
It's not a secret anymore!