Sample 1:
class Animal {
public static void saySomething() { System.out.print(" Gurrr!");
}
}
class Cow extends Animal {
public static void saySomething() {
System.out.print(" Moo!");
}
public static void main(String [] args) {
Animal [] animals = {new Animal(), new Cow()};
for( Animal a : animals) {
a.saySomething();
}
new Cow().saySomething();
}
}
Output is:
Gurrr! Gurrr! Moo!
Sample 2:
class Animal {
public void saySomething() { System.out.print(" Gurrr!");
}
}
class Cow extends Animal {
public void saySomething() {
System.out.print(" Moo!");
}
public static void main(String [] args) {
Animal [] animals = {new Animal(), new Cow()};
for( Animal a : animals) {
a.saySomething();
}
new Cow().saySomething();
}
}
Output:
Gurrr! Moo! Moo!
I just don't understand why making saySomething non-static causes the second call to saySomething invoke the Cow version instead of the Animal version. My understanding was that Gurrr! Moo! Moo!
would be the output in either case.