0

EDIT: Nevermind, I figured it out. Since the method is static, it only looks at the compile time type of the variable and instantiation of it doesn't make a difference.

class Parent {
    void sayIt() {
        System.out.println("Miss ");
    }
}
class Child extends Parent {
    static void sayIt() {
        System.out.println("Hit ");
    }
    public static void main(String args[]) {
        Parent papa = new Parent();
        papa.sayIt();
        Child kid = new Child();
        kid.sayIt();
        papa = kid;
        papa.sayIt();
        kid = (Child)papa;
        kid.sayIt();
    }
}

This prints "Miss Hit Hit Hit". I understand how. But if I change the sayIt() methods to static:

class Parent {
    static void sayIt() {
        System.out.println("Miss ");
    }
}
class Child extends Parent {
    static void sayIt() {
        System.out.println("Hit ");
    }
    public static void main(String args[]) {
        Parent papa = new Parent();
        papa.sayIt();
        Child kid = new Child();
        kid.sayIt();
        papa = kid;
        papa.sayIt();
        kid = (Child)papa;
        kid.sayIt();
    }

Now it prints 'Hit Miss Hit Miss'.

I can't figure out why this might be happening. Any clues?

user1265125
  • 2,608
  • 8
  • 42
  • 65

3 Answers3

0

First of all, the question should never have been inheriting static methods. Inheritance is not for static methods.

You need not have to create an instance for accessing static methods.

Use Parent.sayIt() - For accessing static method written in Parent.java

Use Child.sayIt() - For accessing static method written in Child.java

Raghav
  • 6,893
  • 3
  • 19
  • 28
0

Static methods depend on the reference type not the object type. papa.sayIt(); always print Miss since the compiler will replace it with Parent.sayIt();. Regarding the first case, you are actually hiding the parent method not overriding it.

See: Overriding vs Hiding Java - Confused

Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0

Parent papa = new Parent(); -- represents Parent class and you have static method. when you try to call a static method on on a reference it wont look on object which it holds.

Check here, add these 2 lines and test it.

 Parent p = null;
        p.sayIt();

you don't see NPE and it calls your static method.

Chowdappa
  • 1,580
  • 1
  • 15
  • 31