KaiquanMah commited on
Commit
2722dae
·
verified ·
1 Parent(s): a609561

Overwrite - METHOD, PARAMS

Browse files
Week 5: Class hierarchies/07A. Overwrite and override [Overwrite - METHOD, PARAMS] ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ An essential part of specialisation in the child classes is the MODIFICATION of the FUNCTIONALITY inherited from the parent class.
2
+ In other words, a child class can either ADD completely new features or MODIFY inherited features.
3
+
4
+ Implementing an inherited method in a new child class is called OVERWRITING the method.
5
+
6
+ To overwrite a method, it is sufficient to implement the corresponding method in the inherited class.
7
+ In this case, the objects created from the inherited class will automatically use the 'newer' implementation.
8
+ The method to be overwritten must therefore have
9
+ - the SAME NAME as the original method, and
10
+ - the same list of PARAMETERS as the original method.
11
+
12
+
13
+ The NUMBER, TYPE and ORDER of PARAMETERS must therefore be exactly the same.
14
+ The name of the formal parameters is irrelevant in this context.
15
+
16
+ As a simple example, consider the class Dog with the method bark:
17
+ class Dog {
18
+ public void bark() {
19
+ System.out.println("Bark!");
20
+ }
21
+ }
22
+
23
+
24
+ Let's then write a child class of the Dog class BigDog, with a reimplemented or overwritten barking method:
25
+ class BigDog extends Dog {
26
+ public void bark() {
27
+ System.out.println("WOOF WOOF!");
28
+ }
29
+ }
30
+
31
+
32
+ The version of the method used now depends on the type of object being created:
33
+ public static void main(String[] args) {
34
+ Random r = new Random();
35
+
36
+ Dog snoopy = new Dog();
37
+ BigDog cerberus = new BigDog();
38
+
39
+ snoopy.bark();
40
+ cerberus.bark();
41
+ }
42
+
43
+
44
+ Program outputs:
45
+ Bark!
46
+ WOOF WOOF!
47
+
48
+
49
+
50
+
51
+