• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubts regarding static methods and Inheritance

 
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic