Java Reference
In-Depth Information
Method hiding is subtly different than method overriding. When a method is
overridden, the child version of the method always executes at runtime. Technically, a static
method cannot be overridden because you can still invoke the static method in the parent
class.
For example, the following
FictionBook
class contains the same static method
getCounter
that is declared in its parent class
Book
:
1. //Book.java
2. public class Book {
3. private static int counter = 0;
4. public static int getCounter() {
5. System.out.println(“Inside Book”);
6. return ++ counter;
7. }
8. }
1. //FictionBook.java
2. public class FictionBook extends Book {
3. public static int getCounter() {
4. System.out.println(“Inside FictionBook”);
5. return -1;
6. }
7.
8. public static void main(String [] args) {
9. System.out.println(Book.getCounter());
10. System.out.println(FictionBook.getCounter());
11. }
12. }
Inside
main
,
getCounter
is invoked using both
Book
and
FictionBook
. If
getCounter
was
truly overridden, then the output would be “
Inside FictionBook
” for both method calls.
However, as you can see by the output here, the
getCounter
method in
Book
executes from
line 9:
Inside Book
1
Inside FictionBook
-1
The
getCounter
method in
Book
is referred to as a hidden method, which is probably
not the best term to use because the method is not really hidden at all. You can invoke
getCounter
in
Book
at any time using the syntax
Book.getCounter
, as shown in Figure 2.12.
Search WWH ::
Custom Search