Originally posted by Peter Gade Christensen: static methods are driving me crazy - can someone please shed some light on the subject statement? what is a redefinition and how is it different from overriding...
If I have a static method in Base can I tag it as non static in Derived (extends base) ?
If I have a non static method in Base can I tag it as static in Derived (extends base) ?
Any other pointers/links to static methods / any other threads I can check out
Many thanks for your time and replies!
The answer to both questions is no.
Instance methods (non-static) in base classes can be overridden in derived classes.
This means that if the run-time type of an object is the derived class, then even if the object is being referred to with a base class reference type, the overidden method will be called.
If there is a static method in the derived class that has the same signature as one in the base class, then the type of the reference you use to refer to the object determines which version of the method is called.
the differences in overriding and redefining are only important in polymorph calls of methods, can I state this?
here's an example:
prints out: non-static, Extended Static, Base
The variable "mixed" is polymorph. Its reference type is Base, but its object type is Extended.
Overriding: When a non-static method is called on this variable, the compiler first looks, if such a method exists in the reference type class. Since Base has this method, it could be invoked. But the compiler now looks into the object type class, and if the method is overridden, the method of the object type will be called.
Redefinition: static methods belong to the class only, not to the object. But they can be called through an object (giving me a warning in Eclipse 3.1 by the way). Such methods should be called with the class's name. Should be Extended.statical(); or Base.statical();
The compiler cannot care, what the object type is, it only cares about the reference type and calls the method there. So it is said, that the static method cannot be overridden, just redefined.
And: You cannot mix them up:
Peter Gade Christensen
Joined: Sep 23, 2006
Thanks Keith, BU!!! very helpful and neatly put [ October 21, 2006: Message edited by: Peter Gade Christensen ]