Spaces:
Running
Running
TurkuBasicOOPinJava
/
Week 5: Class hierarchies
/07A. Overwrite and override [Overwrite - METHOD, PARAMS]
| An essential part of specialisation in the child classes is the MODIFICATION of the FUNCTIONALITY inherited from the parent class. | |
| In other words, a child class can either ADD completely new features or MODIFY inherited features. | |
| Implementing an inherited method in a new child class is called OVERWRITING the method. | |
| To overwrite a method, it is sufficient to implement the corresponding method in the inherited class. | |
| In this case, the objects created from the inherited class will automatically use the 'newer' implementation. | |
| The method to be overwritten must therefore have | |
| - the SAME NAME as the original method, and | |
| - the same list of PARAMETERS as the original method. | |
| The NUMBER, TYPE and ORDER of PARAMETERS must therefore be exactly the same. | |
| The name of the formal parameters is irrelevant in this context. | |
| As a simple example, consider the class Dog with the method bark: | |
| class Dog { | |
| public void bark() { | |
| System.out.println("Bark!"); | |
| } | |
| } | |
| Let's then write a child class of the Dog class BigDog, with a reimplemented or overwritten barking method: | |
| class BigDog extends Dog { | |
| public void bark() { | |
| System.out.println("WOOF WOOF!"); | |
| } | |
| } | |
| The version of the method used now depends on the type of object being created: | |
| public static void main(String[] args) { | |
| Random r = new Random(); | |
| Dog snoopy = new Dog(); | |
| BigDog cerberus = new BigDog(); | |
| snoopy.bark(); | |
| cerberus.bark(); | |
| } | |
| Program outputs: | |
| Bark! | |
| WOOF WOOF! | |