Hello
I am preparing for
SCJP 5.0 from K&B and I got on doubt regarding static methods and inheritance. My doubt is does a sub class inherit Super class static methods? If yes then why can't we override static methods in subclass? Why we do not see polymorphic behavior when we assign a sub class object to a super class reference then why doesn't the redefined/overridden method in subclass gets called?
I took this example from K&B.
Ex: class Animal {
static void dostuff() {
System.out.print("a ");
}
}
class Dog extends Animal {
static void dostuff() { // it's a redefinition,
// not an override
System.out.print("d ");
}
public static void main (
String [] args) {
Animal [] a = {new Animal(), new Dog(), new Animal()};
for (int x = 0; x < a.length; x++)
a[x].doStuff(); // invoke the static method
}
}
Running this code produces the output:
a a a
If we can't inherit the static methods from super class in the sub class then can we call
class Animal {
static void doStuff() {
System.out.print("a ");
}
}
class Dog extends Animal {
public static void main (String [] args) {
Dog d = new Dog();
d.doStuff();
}
}
I will be glad to know the answers.
Regards
Padma