CS1020 Lecture Note #7: Object Oriented Programming Inheritance Like father, like son.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

OOP: Inheritance By: Lamiaa Said.
Inheritance Inheritance Reserved word protected Reserved word super
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Writing Classes (Chapter 4)
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
What is inheritance? It is the ability to create a new class from an existing class.
Lecture 8: Object-Oriented Design. 8-2 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Objectives “Good object-oriented programming is really.
Inheritance in C++ Content adapted from a lecture by Dr Soo Yuen Jien.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Topic 4 Inheritance.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
© 2004 Pearson Addison-Wesley. All rights reserved April 10, 2006 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
SUBCLASSES - JAVA. The Purpose of Subclasses Class Farm String getOwner() void setOwner(String s) int getSize() void setSize(int s) Class DairyFarm String.
BY:- TOPS Technologies
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Modern Programming Tools And Techniques-I
Lecture 12 Inheritance.
Inheritance and Polymorphism
03/10/14 Inheritance-2.
03/10/14 Chapter 9 Inheritance.
Week 8 Lecture -3 Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Advanced Programming Behnam Hatami Fall 2017.
Inheritance Inheritance is a fundamental Object Oriented concept
Java Inheritance.
Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism Part 1
Chapter 11 Inheritance and Encapsulation and Polymorphism
Topics OOP Review Inheritance Review Abstract Classes
CIS 110: Introduction to computer programming
Presentation transcript:

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

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

References 3 Textbook Chapter 1: Section 1.4 (pg 54 – 56) Chapter 9: Section 29.1 (pg 480 – 490) CS1020 website  Resources  Lectures ~cs1020/2_resources/lectures.htmlhttp:// ~cs1020/2_resources/lectures.html [CS1020 Lecture 7: Inheritance]

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

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

1. Overriding Methods (revisit) (1/2) 6 Recall in lecture #4 that a user-defined class automatically inherits some methods – such as toString() and equals() – from the Object class 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) However, these inherited methods usually don’t work in the subclass as they are not customised [CS1020 Lecture 7: Inheritance]

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

2. Creating a Subclass (1/6) 8 Object-oriented languages allow inheritance  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  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 [CS1020 Lecture 7: Inheritance]

2. Creating a Subclass (2/6) 9 Recall the BankAcct class in lecture #4 class BankAcct { private int acctNum; private double balance; public BankAcct() { } public BankAcct(int aNum, double bal) {... } public int getAcctNum() {... } public double getBalance() {... } public boolean withdraw(double amount) {...} public void deposit(double amount) {... } public void print() {... } } lect4/BankAcct.java [CS1020 Lecture 7: Inheritance]

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

2. Creating a Subclass (4/6) 11 Duplicating code is undesirable as it is hard to maintain  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:  Code that works on one class cannot work on the other Compilation errors due to incompatible data types Hence, we should create SavingAcct as a subclass of BankAcct [CS1020 Lecture 7: Inheritance]

2. Creating a Subclass (5/6) 12 class BankAcct { protected int acctNum; protected double balance; //Constructors and methods not shown } class SavingAcct extends BankAcct { protected double rate; // interest rate public void payInterest() { balance += balance * rate; } The “extends” keyword indicates inheritance SavingAcct.java BankAcct.java The “protected” keyword allows subclass to access the attributes directly This allows subclass of SavingAcct to access rate. If this is not intended, you may change it to “private”.

2. Creating a Subclass (6/6) 13 The subclass-superclass relationship is known as an “is-a” relationship, i.e. SavingAcct is-a BankAcct In the UML diagram, a solid line with a closed unfilled arrowhead is drawn from SavingAcct to BankAcct The symbol # is used to denoted protected member SavingAcct # rate + getRate() + payInterest() + print() BankAcct # acctNum # balance + getAcctNum() + getBalance() + withdraw() + deposit() + print() [CS1020 Lecture 7: Inheritance]

2.1 Observations 14 Inheritance greatly reduces the amount of redundant coding In SavingAcct class,  No definition of acctNum and balance  No definition of withdraw() and deposit() Improve maintainability:  Eg: If a method is modified in BankAcct class, no changes are needed in SavingAcct class The code in BankAcct remains untouched  Other programs that depend on BankAcct are unaffected  very important! [CS1020 Lecture 7: Inheritance]

2.2 Constructors in Subclass 15 Unlike normal methods, constructors are NOT inherited  You need to define constructor(s) for the subclass class SavingAcct extends BankAcct { protected double rate; // interest rate public SavingAcct(int aNum, double bal, double rate){ acctNum = aNum; balance = bal; this.rate = rate; } //......payInterest() method not shown } SavingAcct.java [CS1020 Lecture 7: Inheritance]

2.3 The “super” Keyword 16 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 SavingAcct extends BankAcct { protected double rate; // interest rate public SavingAcct(int aNum, double bal, double rate){ super(aNum, bal); this.rate = rate; } //......payInterest() method not shown } SavingAcct.java Using the constructor in BankAcct class [CS1020 Lecture 7: Inheritance]

2.4 Using SavingAcct 17 public class TestSavingAcct { public static void main(String[] args) { SavingAcct sa1 = new SavingAcct(2, , 0.03); sa1.print(); sa1.withdraw(50.0); sa1.payInterest(); sa1.print(); } TestSavingAcct.java Inherited method from BankAcct Method in SavingAcct How about print()? Should it be the one in BankAcct class, or should SavingAcct class override it? [CS1020 Lecture 7: Inheritance]

2.5 Method Overriding (1/2) 18 Sometimes we need to modify the inherited method:  To change/extend the functionality  As you already know, this is called method overriding In the SavingAcct class:  The print() method inherited from BankAcct should be modified to include the interest rate in output To override an inherited method:  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) [CS1020 Lecture 7: Inheritance]

2.5 Method Overriding (2/2) 19 The first two lines of code in print() are exactly the same as print() of BankAcct  Can we reuse BankAcct’s print() instead of recoding? class SavingAcct extends BankAcct { protected double rate; // interest rate public double getRate() { return rate; } public void payInterest() {... } public void print() { System.out.println("Account Number: " + getAcctNum()); System.out.printf("Balance: $%.2f\n", getBalance()); System.out.printf("Interest: %.2f%\n", getRate()); } SavingAcct.java [CS1020 Lecture 7: Inheritance]

2.6 Using “super” Again 20 The super keyword can be used to invoke superclass’ method  Useful when the inherited method is overridden class SavingAcct extends BankAcct {... public void print() { super.print(); System.out.printf("Interest: %.2f%\n", getRate()); } SavingAcct.java To use the print() method from BankAcct [CS1020 Lecture 7: Inheritance]

3. Subclass Substitutability (1/2) 21 An added advantage for inheritance is that:  Whenever a super class object is expected, a sub class object is acceptable as substitution! 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:  We can drive a car  Honda is a car (Honda is a subclass of car)  We can drive a Honda [CS1020 Lecture 7: Inheritance]

3. Subclass Substitutability (2/2) 22 public class TestAcctSubclass { public static void transfer(BankAcct fromAcct, BankAcct toAcct, double amt) { fromAcct.withdraw(amt); toAcct.deposit(amt); }; public static void main(String[] args) { BankAcct ba = new BankAcct(1, ); SavingAcct sa = new SavingAcct(2, , 0.03); transfer(ba, sa, ); ba.print(); sa.print(); } TestAcctSubclass.java transfer() method can work on the SavingAcct object sa! [CS1020 Lecture 7: Inheritance]

4. The “Object” Class 23 In Java, all classes are descendants of a predefined class called Object  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 toString() method equals() method  However, these inherited methods usually don’t work because they are not customised [CS1020 Lecture 7: Inheritance]

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

5. “is-a” versus “has-a” (2/2) 25 UML diagrams class BankAcct {... } class SavingAcct extends BankAcct {... } Inheritance: SavingAcct IS-A BankAcct class BankAcct {... }; class Person { private BankAcct myAcct; }; Attribute: Person HAS-A BankAcct SavingAcctBankAcct Solid arrow PersonBankAcct Dotted arrow [CS1020 Lecture 7: Inheritance]

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

7. Constraint of Inheritance in Java 27 Single inheritance: Subclass can only have a single superclass Multiple inheritance: Subclass may have more than one superclass In Java, only single inheritance is allowed (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.) [CS1020 Lecture 7: Inheritance]

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

8. Quick Quiz #1 (2/2) 29 final class ClassC extends ClassB { private int value; public ClassC() { } public ClassC(int val) { super.value = val – 1; value = val; } public void print() { super.print(); System.out.println("Class C: value = " + value); } ClassC.java public class TestSubclasses { public static void main(String[] args) { ClassA objA = new ClassA(123); ClassB objB = new ClassB(456); ClassC objC = new ClassC(789); objA.print(); System.out.println(" "); objB.print(); System.out.println(" "); objC.print(); } TestSubclasses.java  What is the output? ClassA # value + print() ClassB # value + print() ClassC - value + print()

8. Quick Quiz #2 (1/2) 30 Assume all methods print out message of the form, Eg: method m() in class A prints out “A.m”. 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. For each code fragment below, indicate whether:  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? Execution result A a = new A(); a.m(); A.m A a = new A(); a.k(); Method k() not defined in class A A + m() + n() B + p() C + m() D + n() + p() [CS1020 Lecture 7: Inheritance]

8. Quick Quiz #2 (2/2) 31 Code fragmentCompilation error?Execution result A a = new C(); a.m(); B b = new A(); b.n(); A a = new B(); a.m(); 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();  A + m() + n() B + p() C + m() D + n() + p() [CS1020 Lecture 7: Inheritance]

Summary 32 Inheritance:  Creating subclasses  Overriding methods  Using “super” keyword  The “Object” class [CS1020 Lecture 7: Inheritance]

Practice Exercise 33 Practice Exercises  #22: Create a subclass CentredCircle from a given class Circle  #23: Manage animals [CS1020 Lecture 7: Inheritance]

End of file