• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubts regarding static methods and Inheritance  RSS feed

 
Padma Asrani
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods in the superclass that are visible to the subclass are inherited.

However, it is specifically stated in the Java Language Specification how static method invocations are treated.

In particular, the type of the reference is used to determine which method to call for static methods.

This is different from the behavior with overridden instance methods. The runtime type of the reference is used to determine which method to invoke.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!