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?