Java Reference
In-Depth Information
FIGURE 2.12 The static getCounter method in FictionBook does not override
getCounter in Book.
Book.getCounter()
invokes the method
in Book.
Book
public static int getCounter()
FictionBook.getCounter()
invokes the method
in FictionBook.
FictionBook
public static int getCounter()
Nonetheless, method hiding is the term used to describe this situation.
Overridden vs. Hidden
When a child class contains the same instance method as a parent class instance method
(assuming all the rules of method overriding are followed), the child class method
overrides the parent class method. When a child class contains a static method that is the
same as a static method in the parent, this child method hides the parent class method.
In simpler terms, instance methods are overridden and static methods are hidden.
A child class cannot contain a nonstatic version of a static method in its parent class.
Neither can a child class contain a static method with the same version of a nonstatic
method in the parent. Either of these situations generates a compiler error.
Final Methods
A method in Java can be declared fi nal using the final keyword. A fi nal method cannot be
overridden. You might make a method fi nal if it has a critical implementation that should
not be changed, or you might just want a child class not to have the option of overriding
a particular method. Whatever the motivation, an attempt to override a fi nal method
generates a compiler error.
The following Lion class has a fi nal method named breathe :
1. public class Lion {
2. public void eat(String something) {
3. System.out.println(“Lion is eating”);
4. }
Search WWH ::




Custom Search