0

What should be printed when we execute this code? I picked the question from here where the answer is provided but I kinda believe is wrong. First the call to a static function has to be done in static way, second when we override a static function the previous one is no longer accessible ( no new memory is assigned)

class Base {
    public static void show() {
       System.out.println("Base::show() called");
    }
}

class Derived extends Base {
    public static void show() {
       System.out.println("Derived::show() called");
    }
}

class Main {
    public static void main(String[] args) {
        Base b = new Derived();;
        b.show();
    }
}
C graphics
  • 7,308
  • 19
  • 83
  • 134

1 Answers1

0

static method belongs to class itself and overriding works for instance methods only. If you define the same method again in sub-class then it's called re-defining hiding of the static method.

static method looks for class to invoke it and that can be verified by below same code:

Base b = null;
b.show();  // Base::show() called

It doesn't make any sense to call static method via object.

Braj
  • 46,415
  • 5
  • 60
  • 76
  • 1
    Actually, it's called "hiding". Not "redefining". See http://docs.oracle.com/javase/tutorial/java/IandI/override.html and http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.8 – JB Nizet Sep 06 '14 at 20:39
  • @JBNizet Thanks let me read. – Braj Sep 06 '14 at 20:39
  • @JBNizet thanks for correcting me. Most of time I read in books about redefining. May be they used wrong term. – Braj Sep 06 '14 at 20:41