Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static method overriding static method

 
Dan Culache
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An answer in the study guide by Heller and Roberts says that "static methods cannot override static methods" but the following code works just fine. Any thoughts?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried:

?
 
Pallavi Chakraborty
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dan, Barry,
I tried compiling with
H h = new G();
h.m();
It is giving an error saying h is already defined in Class4.
But I did find something in API documentation.
http://java.sun.com/docs/books/tutorial/java/javaOO/override.html
It says :
Also, a subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method.
A subclass can hide a static method in the superclass by declaring a static method in the subclass with the same signature as the static method in the superclass
What does it mean when they say hiding a static method with the same signature.
Pallavi
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods do not participate in polymorphism therefore they are hidden not overridden.
This is one place where C# has Java beat. In C# you can't run static methods (which are class methods) with an object reference.
Think about how we normally execute static methods. We don't do:
H h = new H();
h.m();
we do:
H.m();
Try this: the method that gets executed is determined at compile time for static methods. So when you do something like:
H h = new G();
h.m();
Since h is a pointer to an H object, it is the static method of the H class that will be executed, not the static method of the G class. That is because at compile time the compiler has no idea that h is pointing to a G object.
Static methods don't participate in polymorphism therefore they can't be overridden. They can only be hidden.
 
Dan Culache
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good point, thank you all.
I guess Thomas is right, if you couldn't call a static method using an object reference this would not be confusing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic