Introduction to Method Overriding
Method overriding is an important feature of Java language. Its very imporntant concept of object-oriented programming.
When a method of superclass with the same signature (name, plus the number and the type of its parameters) and return type is reimplemented in subclass, its called method overriding.
The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides.
When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.
Syntax
class SuperClass {
//fields and constructor declaration
void show() {
statement(s);
}
}
class SubClass extends SuperClass {
//fields and constructor declaration
// Override method
void show() {
statement(s);
}
}
Example
1. /**
2. * @(#)OverrideDemo.java
3. *
4. *
5. * @author
6. * @version 1.00 2009/11/19
7. */
8.
9. class Animal {
10.
11. public static void testClassMethod() {
12. System.out.println("The class method in Animal.");
13. }
14.
15. public void testInstanceMethod() {
16. System.out.println("The instance method in Animal.");
17. }
18.
19. }
20.
21. class Cat extends Animal {
22.
23. public static void testClassMethod() {
24. System.out.println("The class method in Cat.");
25. }
26.
27. public void testInstanceMethod() {
28. System.out.println("The instance method in Cat.");
29. }
30.
31. }
32.
33. public class OverrideDemo {
34.
35. /**
36. * Creates a new instance of OverrideDemo.
37. */
38. public OverrideDemo() {
39. }
40.
41. /**
42. * @param args the command line arguments
43. */
44. public static void main(String[] args) {
45. // TODO code application logic here
46.
47. Cat myCat = new Cat();
48.
49. Animal myAnimal = myCat;
50.
51. Animal.testClassMethod();
52. myAnimal.testInstanceMethod();
53.
54.
55. }
56. }
Output
The class method in Animal.
The instance method in Cat.
