KaiquanMah commited on
Commit
0376331
·
verified ·
1 Parent(s): 85b4d47

class SubClass1 extends ParentClass { }

Browse files
Week 5: Class hierarchies/02A Inheritance in Java ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ In Java, each class can DIRECTLY INHERIT UP TO 1 CLASS.
2
+ In fact, in Java, every class inherits (unless otherwise specified) the PARENT CLASS 'Object'.
3
+ Thus, all Java classes are DIRECT OR INDIRECT heirs of the class 'Object'.
4
+
5
+ Inheritance is indicated by the keyword 'extends'.
6
+ In fact, the English version is perhaps clearer in meaning than inheritance:
7
+ the INHERITING/CHILD class 'extends' the functionality of the PARENT class,
8
+ since new properties can be added to the child class in addition to those of the parent class.
9
+
10
+
11
+
12
+ As an example, let us first consider the class 'Person'.
13
+ The class constructor is currently empty, we will return to this later:
14
+ class Person {
15
+ private String name;
16
+ private String email;
17
+
18
+ // CONSTRUCTOR - EMPTY
19
+ public Person() {}
20
+
21
+ public String getName() {
22
+ return name;
23
+ }
24
+
25
+ public void setName(String name) {
26
+ this.name = name;
27
+ }
28
+
29
+ public String getEmail() {
30
+ return email;
31
+ }
32
+
33
+ public void setEmail(String email) {
34
+ this.email = email;
35
+ }
36
+ }
37
+
38
+
39
+ Now you can define the class Student, which inherits the Person class.
40
+ So the Student class has all the features of the Person class (but no new implementation of its own yet).
41
+ class Student extends Person { }
42
+
43
+
44
+ Similarly, a class Teacher can be defined, which also inherits the Person class.
45
+ The teacher now also has all the attributes of a person:
46
+ class Teacher extends Person { }
47
+
48
+
49
+