| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
Can static methods be overridden?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
Can static methods be overridden?The static methods can not be overridden! If a subclass defines a static method with the same signature as a static method in the superclass, the method in the subclass hides the one in the superclass. The distinction between hiding and overriding has important implications.
Let's look at an example. This example contains two classes. The first is
The second class, a subclass of
The output results are: Create a Cat instance ... The hide method in Cat. The hide method in Cat. The override method in Cat. Cast the Cat instance to Animal... The hide method in Animal. The hide method in Animal. The override method in Cat. Create an Animal instance.... The hide method in Animal. The hide method in Animal. The override method in Animal. There are three sections in this example. The first and third ones are normal. The second one is wired one, we cast the Cat type instance to it's parent Animal type. myAnimal.hide() invoke the static method defined in the Animal class. If this method were truly overridden, we should have invoked static hide() method defined in Cat class, but we didn't. It is considered bad style to call static methods on instances because hiding
can be confusing. So it is better to use the class, for example The hide method in Animal. The override method in Cat. The version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass. For class methods, the runtime system invokes the method defined in the compile-time
type of the reference on which the method is called. In other words,
call to static methods are mapped at the compile time and depends on the
declared type of the reference(Parent in this case) and not the instance the
reference points at runtime. In the example, the compile-time type of For instance methods, the runtime system invokes the method defined in the runtime
type of the reference on which the method is called. In the example,
the runtime type of An instance method cannot override a static method, and a static method cannot hide an instance method. The following table summarizes what happens when you define a method with the same signature as a method in a superclass. How to access the static methods defined in the superclass? A hidden method can be accessed by using a qualified name or by using a method
invocation expression that contains the keyword
|