Java Reference
In-Depth Information
Method Hiding
A class also inherits all non-private static methods from its superclass. Redefining an inherited static method in a
class is known as method hiding. The redefined static method in a subclass is said to hide the static method of its
superclass. Recall that redefining a non-static method in a class is called method overriding. Listing 16-26 contains
code for a
MHidingSuper
class, which has a
static print()
method. Listing 16-27 has the code for a
MHidingSub
class
that inherits from the
MHidingSuper
class. It redefines the
print()
method, which hides the
print()
method in the
MHidingSuper
class. The
print()
method in
MHidingSub
is an example of method hiding.
Listing 16-26.
A MHidingSuper Class That Has a Static Method
// MHidingSuper.java
package com.jdojo.inheritance;
public class MHidingSuper {
public static void print() {
System.out.println("Inside MHidingSuper.print()");
}
}
Listing 16-27.
A MHidingSub Class That Hides the print() of its Superclass
// MHidingSub.java
package com.jdojo.inheritance;
public class MHidingSub extends MHidingSuper {
public static void print() {
System.out.println("Inside MHidingSub.print()");
}
}
All rules about the redefined method (name, access level, return types, and exception) for method hiding are
the same as for method overriding. Please refer to the “Method Overriding” section for more detailed discussion on
these rules. One rule that is different for method hiding is the binding rule. Early binding is used for
static
methods.
Based on the compile-time type of the expression, the compiler determines what code will be executed at runtime
for a
static
method call. Note that you can use the class name as well as a reference variable to invoke a
static
method. There is no ambiguity about method binding, when you use a class name to invoke a
static
method. The
compiler binds the
static
method that is defined (or redefined) in the class. If a class does not define (or redefine)
the
static
method, the compiler binds the method that the class inherits from its superclass. If the compiler does
not find a defined/redefined/inherited method in the class, it generates an error. Listing 16-28 contains the code that
demonstrates the early binding rules for method hiding for
static
methods of a class.
Listing 16-28.
A Test Class to Demonstrate Method Hiding
// MHidingTest.java
package com.jdojo.inheritance;
public class MHidingTest {
public static void main(String[] args) {
MHidingSuper mhSuper = new MHidingSub();
MHidingSub mhSub = new MHidingSub();