CS 1020 Lecture Note 7 Object Oriented Programming

CS 1020 Lecture Note #7: Object Oriented Programming Inheritance Like father, like son

Objectives § Introducing inheritance through creating subclasses § Improve code reusability § Allowing overriding to replace the implementation of an inherited method [CS 1020 Lecture 7: Inheritance] 2

References Textbook • Chapter 1: Section 1. 4 (pg 54 – 56) • Chapter 9: Section 29. 1 (pg 480 – 490) CS 1020 website Resources Lectures • http: //www. comp. nus. edu. sg/ ~cs 1020/2_resources/lectures. html [CS 1020 Lecture 7: Inheritance] 3

Outline 1. Overriding Methods (revisit) 2. Creating a Subclass 2. 1 2. 2 2. 3 2. 4 2. 5 2. 6 3. 4. 5. 6. 7. 8. Observations Constructors in Subclass The “super” Keyword Using Saving. Acct Method Overriding Using “super” Again Subclass Substitutability The “Object” Class “is-a” versus “has-a” Preventing Inheritance (“final”) Constraint of Inheritance in Java Quick Quizzes [CS 1020 Lecture 7: Inheritance] 4

0. Object-Oriented Programming n Four fundamental concepts of OOP: q q Encapsulation Abstraction Inheritance Polymorphism n Inheritance allows new classes to inherit properties of existing classes n Main concepts in inheritance q q Subclassing Overriding [CS 1020 Lecture 7: Inheritance] 5

1. Overriding Methods (revisit) (1/2) n Recall in lecture #4 that a user-defined class automatically inherits some methods – such as to. String() and equals() – from the Object class n The Object class is known as the parent class (or superclass); it specifies some basic behaviours common to all kinds of objects, and hence these behaviours are inherited by all its subclasses (derived classes) n However, these inherited methods usually don’t work in the subclass as they are not customised [CS 1020 Lecture 7: Inheritance] 6

1. Overriding Methods (revisit) (2/2) n Hence, to make them work, we customised these inherited methods – this is called overriding Lecture #4: My. Ball/My. Ball. java /********* Overriding methods *********/ // Overriding to. String() method public String to. String() { return "[" + get. Colour() + ", " + get. Radius() + "]"; } // Overriding equals() method public boolean equals(Object obj) { if (obj instanceof My. Ball) { My. Ball ball = (My. Ball) obj; return this. get. Colour(). equals(ball. get. Colour()) && this. get. Radius() == ball. get. Radius(); } else return false; } } [CS 1020 Lecture 7: Inheritance] 7

2. Creating a Subclass (1/6) n Object-oriented languages allow inheritance q q n Declare a new class based on an existing class So that the new class may inherit all of the attributes and methods from the other class Terminology q q If class B is derived from class A, then class B is called a child (or subclass or derived class) of class A Class A is called a parent (or superclass) of class B [CS 1020 Lecture 7: Inheritance] 8

2. Creating a Subclass (2/6) n Recall the Bank. Acct class in lecture #4 class Bank. Acct { private int acct. Num; private double balance; lect 4/Bank. Acct. java public Bank. Acct() { } public Bank. Acct(int a. Num, double bal) {. . . } public int get. Acct. Num() {. . . } public double get. Balance() {. . . } public boolean withdraw(double amount) {. . . } public void deposit(double amount) {. . . } public void print() {. . . } } [CS 1020 Lecture 7: Inheritance] 9

2. Creating a Subclass (3/6) n Let’s define a Saving. Acct class n Basic information: q q n Basic functionality: q q n New requirements Withdraw, deposit Pay interest Compare with the basic bank account: q q n Account number, balance Interest rate Differences are highlighted above Saving. Acct shares more than 50% of the code with Bank. Acct So, should we just cut and paste the code from Bank. Acct to create Saving. Acct? [CS 1020 Lecture 7: Inheritance] 10

2. Creating a Subclass (4/6) n Duplicating code is undesirable as it is hard to maintain q q n Need to correct all copies if errors are found Need to update all copies if modifications are required Since the classes are logically unrelated if the codes are separated: q Code that works on one class cannot work on the other n Compilation errors due to incompatible data types n Hence, we should create Saving. Acct as a subclass of Bank. Acct [CS 1020 Lecture 7: Inheritance] 11

2. Creating a Subclass (5/6) class Bank. Acct { protected int acct. Num; protected double balance; Bank. Acct. java The “protected” keyword allows subclass to access the attributes directly //Constructors and methods not shown } The “extends” class Saving. Acct extends Bank. Acct { keyword indicates inheritance protected double rate; // interest rate public void pay. Interest() { balance += balance * rate; } This allows subclass of Saving. Acct to access rate. If this is not intended, } you may change it to “private”. [CS 1020 Lecture 7: Inheritance] Saving. Acct. java 12

2. Creating a Subclass (6/6) n The subclass-superclass relationship is known as an “is -a” relationship, i. e. Saving. Acct is-a Bank. Acct n In the UML diagram, a solid line with a closed unfilled arrowhead is drawn from Saving. Acct to Bank. Acct n The symbol # is used to denoted protected member Saving. Acct # rate + get. Rate() + pay. Interest() + print() [CS 1020 Lecture 7: Inheritance] Bank. Acct # acct. Num # balance + get. Acct. Num() + get. Balance() + withdraw() + deposit() + print() 13

2. 1 Observations n Inheritance greatly reduces the amount of redundant coding n In Saving. Acct class, q q n Improve maintainability: q n No definition of acct. Num and balance No definition of withdraw() and deposit() Eg: If a method is modified in Bank. Acct class, no changes are needed in Saving. Acct class The code in Bank. Acct remains untouched q Other programs that depend on Bank. Acct are unaffected very important! [CS 1020 Lecture 7: Inheritance] 14

2. 2 Constructors in Subclass n Unlike normal methods, constructors are NOT inherited q You need to define constructor(s) for the subclass Saving. Acct extends Bank. Acct { protected double rate; // interest rate public Saving. Acct(int a. Num, double bal, double rate){ acct. Num = a. Num; balance = bal; this. rate = rate; } //. . . pay. Interest() method not shown } Saving. Acct. java [CS 1020 Lecture 7: Inheritance] 15

2. 3 The “super” Keyword n n The “super” keyword allows us to use the methods (including constructors) in the superclass directly If you make use of superclass’ constructor, it must be the first statement in the method body class Saving. Acct extends Bank. Acct { protected double rate; // interest rate public Saving. Acct(int a. Num, double bal, double rate){ super(a. Num, bal); Using the constructor this. rate = rate; } in Bank. Acct class //. . . pay. Interest() method not shown } Saving. Acct. java [CS 1020 Lecture 7: Inheritance] 16

2. 4 Using Saving. Acct public class Test. Saving. Acct { Test. Saving. Acct. java public static void main(String[] args) { Saving. Acct sa 1 = new Saving. Acct(2, 1000. 0, 0. 03); sa 1. print(); sa 1. withdraw(50. 0); sa 1. pay. Interest(); sa 1. print(); Inherited method from Bank. Acct Method in Saving. Acct } } How about print()? Should it be the one in Bank. Acct class, or should Saving. Acct class override it? [CS 1020 Lecture 7: Inheritance] 17

2. 5 Method Overriding (1/2) n Sometimes we need to modify the inherited method: q q n In the Saving. Acct class: q n To change/extend the functionality As you already know, this is called method overriding The print() method inherited from Bank. Acct should be modified to include the interest rate in output To override an inherited method: q q Simply recode the method in the subclass using the same method header Method header refers to the name and parameters type of the method (also known as method signature) [CS 1020 Lecture 7: Inheritance] 18

2. 5 Method Overriding (2/2) class Saving. Acct extends Bank. Acct { protected double rate; Saving. Acct. java // interest rate public double get. Rate() { return rate; } public void pay. Interest() {. . . } public void print() { System. out. println("Account Number: " + get. Acct. Num()); System. out. printf("Balance: $%. 2 fn", get. Balance()); System. out. printf("Interest: %. 2 f%%n", get. Rate()); } } n The first two lines of code in print() are exactly the same as print() of Bank. Acct q Can we reuse Bank. Acct’s print() instead of recoding? [CS 1020 Lecture 7: Inheritance] 19

2. 6 Using “super” Again n The super keyword can be used to invoke superclass’ method q Useful when the inherited method is overridden class Saving. Acct extends Bank. Acct {. . . Saving. Acct. java To use the print() method from Bank. Acct public void print() { super. print(); System. out. printf("Interest: %. 2 f%%n", get. Rate()); } } [CS 1020 Lecture 7: Inheritance] 20

3. Subclass Substitutability (1/2) n An added advantage for inheritance is that: q Whenever a super class object is expected, a sub class object is acceptable as substitution! n q n Caution: the reverse is NOT true (Eg: A cat is an animal; but an animal may not be a cat. ) Hence, all existing functions that works with the super class objects will work on subclass objects with no modification! Analogy: q q q We can drive a car Honda is a car (Honda is a subclass of car) We can drive a Honda [CS 1020 Lecture 7: Inheritance] 21

3. Subclass Substitutability (2/2) public class Test. Acct. Subclass { Test. Acct. Subclass. java public static void transfer(Bank. Acct from. Acct, Bank. Acct to. Acct, double amt) { from. Acct. withdraw(amt); to. Acct. deposit(amt); }; public static void main(String[] args) { Bank. Acct ba = new Bank. Acct(1, 234. 56); Saving. Acct sa = new Saving. Acct(2, 1000. 0, 0. 03); transfer(ba, sa, 123. 45); ba. print(); sa. print(); } transfer() method can work on the Saving. Acct object sa! } [CS 1020 Lecture 7: Inheritance] 22

4. The “Object” Class n In Java, all classes are descendants of a predefined class called Object q q Object class specifies some basic behaviors common to all objects Any methods that works with Object reference will work on object of any class Methods defined in the Object class are inherited in all classes Two inherited Object methods are n n q to. String() method equals() method However, these inherited methods usually don’t work because they are not customised [CS 1020 Lecture 7: Inheritance] 23

5. “is-a” versus “has-a” (1/2) n Words of caution: q q Do not overuse inheritance Do not overuse protected n n Make sure it is something inherent for future subclass To determine whether it is correct to inherit: q Use the “is-a” rules of thumb n q If “B is-a A” sounds right, then B is a subclass of A Frequently confused with the “has-a” rule n If “B has-a A” sounds right, then B should have an A attribute (hence B depends on A) [CS 1020 Lecture 7: Inheritance] 24

5. “is-a” versus “has-a” (2/2) n UML diagrams class Bank. Acct {. . . } class Saving. Acct extends Bank. Acct {. . . } Saving. Acct Bank. Acct Solid arrow Inheritance: Saving. Acct IS-A Bank. Acct class Bank. Acct {. . . }; class Person { private Bank. Acct my. Acct; }; Person Bank. Acct Dotted arrow Attribute: Person HAS-A Bank. Acct [CS 1020 Lecture 7: Inheritance] 25

6. Preventing Inheritance (“final”) n Sometimes, we want to prevent inheritance by another class (eg: to prevent a subclass from corrupting the behaviour of its superclass) n Use the final keyword q n Eg: final class Saving. Acct will prevent a subclass to be created from Saving. Acct Sometimes, we want a class to be inheritable, but want to prevent some of its methods to be overridden by its subclass q Use the final keyword on the particular method: public final void pay. Interest() { … } will prevent the subclass of Saving. Acct from overriding pay. Interest() [CS 1020 Lecture 7: Inheritance] 26

7. Constraint of Inheritance in Java n Single inheritance: Subclass can only have a single superclass n Multiple inheritance: Subclass may have more than one superclass n In Java, only single inheritance is allowed n (Side note: Java’s alternative to multiple inheritance can be achieved through the use of interfaces – to be covered later. A Java class may implement multiple interfaces. ) [CS 1020 Lecture 7: Inheritance] 27

8. Quick Quiz #1 (1/2) class Class. A { protected int value; public Class. A() { Class. A. java Class. A # value } public Class. A(int val) { value = val; } public void print() { System. out. println("Class A: value = " + value); } } Class. B # value + print() class Class. B extends Class. A { protected int value; public Class. B() { + print() } public Class. B(int val) { super. value = val – 1; value = val; } public void print() { super. print(); System. out. println("Class B: value = " + value); } } Class. B. java [CS 1020 Lecture 7: Inheritance] 28

8. Quick Quiz #1 (2/2) final class Class. C extends Class. B { private int value; public Class. C() { Class. C. java + print() } Class. B # value public Class. C(int val) { super. value = val – 1; value = val; } + print() public void print() { super. print(); System. out. println("Class C: value = " + value); } } Class. A # value What is the output? Class. C - value + print() public class Test. Subclasses { public static void main(String[] args) { Class. A obj. A = new Class. A(123); Class. B obj. B = new Class. B(456); Class. C obj. C = new Class. C(789); obj. A. print(); System. out. println("-----"); obj. B. print(); System. out. println("-----"); obj. C. print(); } } [CS 1020 Lecture 7: Inheritance] Test. Subclasses. java 29

8. Quick Quiz #2 (1/2) A + m() + n() n Assume all methods print out message of the form <class name>, <method name> n Eg: method m() in class A prints out “A. m”. B C n If a class overrides an inherited method, the method’s name will appear in the class icon. Otherwise, the inherited method remains unchanged in the subclass. + n() + p() + m() n For each code fragment below, indicate whether: q q The code will cause compilation error, and briefly explain; or The code can compile and run. Supply the execution result. Code fragment (example) Compilation error? Why? A a = new A(); a. m(); A a = new A(); a. k(); [CS 1020 Lecture 7: Inheritance] D + m() + n() + p() Execution result A. m Method k() not defined in class A 30

8. Quick Quiz #2 (2/2) Code fragment A a = new C(); a. m(); B b = new A(); b. n(); A a = new B(); a. m(); Compilation error? Execution result A + m() + n() B + n() + p() C + m() D + m() + n() + p() A a; C c = new D(); a = c; a. n(); B b = new D(); b. p(); C c = new C(); c. n(); A a = new D(); a. p(); [CS 1020 Lecture 7: Inheritance] 31

Summary n Inheritance: q q Creating subclasses Overriding methods Using “super” keyword The “Object” class [CS 1020 Lecture 7: Inheritance] 32

Practice Exercise n Practice Exercises q q #22: Create a subclass Centred. Circle from a given class Circle #23: Manage animals [CS 1020 Lecture 7: Inheritance] 33

End of file
- Slides: 34