1 Inheritance Chapter 9. 2 What You Will Learn Software reusability (Recycling) Inheriting data members and functions from previously defined classes.

Slides:



Advertisements
Similar presentations
Outline 1 Introduction 2 Base Classes and Derived Classes 3 protected Members 4 Relationship between Base Classes and Derived Classes 5 Case Study: Three-Level.
Advertisements

Chapter 13 - Inheritance. Goals To learn about inheritance To learn about inheritance To understand how to inherit and override superclass methods To.
Chapter 19 - Inheritance Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Inheritance Part I. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
C++ Inheritance Gordon College CPS212. Basics OO-programming can be defined as a combination of Abstract Data Types (ADTs) with Inheritance and Dynamic.
Inheritance Definition Relationships Member Access Control Data Encapsulation Overloading vs. Overriding Constructors & Destructors.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
I NHERITANCE Chapter 10. I NHERITANCE Mechanism for enhancing existing classes You need to implement a new class You have an existing class that represents.
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
C++ Inheritance Systems Programming.
You gotta be cool. Inheritance Base Classes and Derived Classes Inheritance: Public, Protected, Private What is inherited from the base class? Multiple.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Object-Oriented PHP (1)
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved OOP and.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Object Oriented Programming: Inheritance Chapter 9.
Programming Languages and Paradigms Object-Oriented Programming.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
1 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Chapter 11: Inheritance and Composition. Objectives In this chapter, you will: – Learn about inheritance – Learn about derived and base classes – Redefine.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Chapter 8 More Object Concepts
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
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.
Inheritance. Lecture contents Inheritance Class hierarchy Types of Inheritance Derived and Base classes derived class constructors protected access identifier.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
1 Introduction to Classes and Objects Chapter 3 Introduction to Classes and Objects Chapter 3.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Chapter 4 Introduction to Classes, Objects, Methods and strings
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Inheritance Outline 9.1Introduction 9.2Inheritance: Base Classes and Derived Classes 9.3.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Department of Computer Science Data Structures Using C++ 2E Chapter 2 Object-Oriented Design (OOD) and C++  Learn about inheritance  Learn about derived.
Object Oriented Programming: Inheritance Chapter 9.
1 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 10 More on Objects and Classes.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 10 More on Objects and Classes.
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Chapter 11: Inheritance and Composition. Introduction Two common ways to relate two classes in a meaningful way are: – Inheritance (“is-a” relationship)
Inheritance ndex.html ndex.htmland “Java.
Object-Oriented Programming: Inheritance and Polymorphism.
Object Oriented Programming: Inheritance Chapter 9.
Part -1 © by Pearson Education, Inc. All Rights Reserved.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Object Oriented Programming: Inheritance
Computing with C# and the .NET Framework
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Learning Objectives Inheritance Virtual Function.
Lecture 22 Inheritance Richard Gesick.
Object Oriented Programming: Inheritance
Chapter 19 - Inheritance Outline 19.1 Introduction
Fundaments of Game Design
Chapter 11: Inheritance and Composition
COP 3330 Object-oriented Programming in C++
Presentation transcript:

1 Inheritance Chapter 9

2 What You Will Learn Software reusability (Recycling) Inheriting data members and functions from previously defined classes

3 Introduction Software Reusability –saves time in program development –encourages use of proven, debugged code –reduces problems Write programs in general fashion Enables software designers to deal with complexity of modern software

4 Introduction When creating a new class … –designate that class to inherit data members, functions of previously defined base class –result is a derived class Class can be derived from one or multiple classes Derived class adds new data members and functions Replace and refine existing members

5 Base Classes & Derived Classes Base classis more general –student, shape, loan Derived class is more specific –grad student, undergrad –circle, triangle, rectangle –carloan, home improvement, mortgage Some languages talk of –Superclass (base class) –Subclass (derived class)

6 Derived Classes -- Example Base Classes Derived classes

7 Base Classes & Derived Classes Inheritance produces tree like structures - Checking & Savings are derived from Bank Account Class - Super-Now class derived from Checking class - Checking & Savings are derived from Bank Account Class - Super-Now class derived from Checking class

8 Design Tip Important link between derived class and base class –The “IS-A” relationship Examples –A checking account IS-A banking account –A savings account IS NOT a checking account If there is no IS-A relationship, do not use inheritance

9 Declaring Derived Classes Format class :public { }; // End class

10 Bank Account Class Function Members –make a deposit –access account number –access account balance Data members –account number –account balance

11 Checking Account Class Function Members –constructor to initialize data –cash a check (receive amt, debit balance) Data members –minimum balance, dictates per-check charge –per check charge amt

12 Super-Now Checking Class Function members –constructor to initialize Super-Now data –function to credit interest to account if balance above required minimum Data members –interest rate for balance above minimum

13 Savings Account Class Function Members –constructor –function to credit interest to account –function to debit account for withdrawal Data Members –annual interest rate (compounded monthly)

14 Base Class Declared #ifndef ACCOUNT_H #define ACCOUNT_H CLASS BankAccount{ public: void Deposit (float Dep); int AccountNum( ); float CurrentBalance ( ); protected: int AccountNumber float Balance; }; #endif Note preprocessor directives Note new category protected:

15 Base Class Declared Preprocessor statements –this header will be included in several additional files Note no constructor –properly used inheritance will not declare instances of base classes –no instances created ==> abstract class

16 Base Class Declared Protected Member –accessible to base class –accessible to any derived class Thus accessible to any class within class family NOT accessible to things outside the class family

17 Checking Class Declared #include “account.h” class Checking:public BankAccount { public: Checking (int AcctNum = 0000, float Bal = 0, float Min = 1000., float Chg =.5); void CashCheck (float Amt); protected: float Minimum; float Charge; }; Note : public base class allows all public members of base class to be public in derived class

18 Public Base Class Designated as public in derived class declaration Inherited members of public base class maintain access level in derived class –inherited protected (or public) members remain protected (or public ) Clients of derived class can invoke base class operations on derived class objects

19 Base Class not public Public members of the base class are not public members of the derived class Clients of the derived class cannot invoke base class operations on derived class objects

20 Protected vs. Public Protected –in base class declaration –allows access to protected members of base class by derived class –protected members accessible within class family Public –for declaring derived class –public members of the base class are public for derived class

21 Super-Now Derived Class #include “checking.h” class SuperNow : public Checking { public : SuperNow (int AcctNum = 0, float Bal = 0, float Min = , float Chg =.5 float Rate = 12.0); void AddInterest( ); protected : float InterestRate; }; Note: this class inherits all the protected variables from Checking and BankAcct classes

22 Savings Derived Class #include “account.h” class Savings : public BankAccount { public : Savings (int AcctNum = 0, float Bal = 0, float Rate = 12.0); void AddInterest( ); void Withdraw (float Amt); protected: float InterestRate; } ; Savings inherits all protected variables from BankAcct

23 Class Family Hierarchy BankAcct Deposit( ) Account_Num( ) Current_Balance( ) Account_Number Balance Savings Savings( ) Add_Interest( ) Withdraw( ) Interest_rate Checking Checking( ) Cash_Check( ) Minimum Charge Super_Now Super_Now( ) Add_Interest( ) Interest_rate

24 Protected Members Public members accessible by –all functions in the program Private members of base class accessible by –member functions –friends of the base class Protected members –intermediate level of protection –accessible by members, friends of base class –and by members, friends of derived classes

25 Protected Members Derived class members can refer to –public members –protected members of base class –simply use member names "Protected" items do away with encapsulation Text recommends use of protected classification as last resort

26 Casting Pointers Consider an instance of a derived class –can be treated as an object of its base class This means if we have an array of pointers to the base class, we could store pointers to objects of a variety of derived classes Reverse is not true … –a base class object is not also automatically a derived class object

27 Casting Pointers Note Figure casting base-class pointers Use unary operator static_cast ( object) –Lines 88, 118, 127 Review program description in text, on audio description of Text CD Note errors (garbage values) which can result from casting in the wrong direction

28 Using Member Functions If an object is private to the base class, compiler will forbid access by member of derived class -- this is encapsulation How will a derived class object access private data of base class? It will not! It won't -- directly anyway It must use available modifier functions

29 Overriding Base-Class Members Inside a derived class you can have a new version of a function in the base class Which function is used (from derived class or base class) is determined by context -- by scope of the call Possible to call function in base class by use of scope operator :: Note figure 9.5, Overriding base class member function -- listen to audio on text CD

30 Public, Protected, Private Inheritance We will use mainly public inheritance –can also have protected and private inheritance Recall figure 9.4, line 49 Public and protected members of Point are inherited as public and protected members into Circle -- private members of base class are hidden class Circle : public Point { // Circle inherits from Point

31 Direct, Indirect Base Classes Direct base class –one level above in hierarchy –specified in derived class's header with colon when declared Indirect base class –does not show up in the declaration –is two or more levels up in the hierarchy

32 Constructors & Destructors Recall declaration of constructor of Circle –it in turn called the constructor of Point Base constructor called implicitly first Then derived class constructor executed Finally, body of derived class’s constructor is executed Circle::Circle (double r, int a, int b) : Point (a,b)

33 Constructors & Destructors If base class constructor requires parameters, these parameters must be passed by derived class’s constructor Note that our example with Checking and Super-Now did not operate this way (actually we didn't see the implementation)

34 Constructors & Destructors Body of derived class destructor executed Destructors for member objects (if any) executed Finally, base class’s destructor is executed Note: this is opposite sequence as for constructors

35 Implicit Derived to Base- Class Conversion Under public inheritance, derived class- objects can be treated as base-class objects –possible to assign checking object to bank account object –error: trying to access checking acct members from the bank acct object Cannot assign in the other direction However, can be made legit with properly designed overloaded = operator

36 Mix & Match base- and derived-class pointers Refer to base-class object w/base-class pointer … OK Refer to derived-class object w/derived- class pointer … OK Refer to derived-class obj w/base-class pointer … safe – checking account object is also a bank account object –can only reference base class members Refer to base-class obj w/derived-class pointer … ERROR

37 Implicit Derived to Base- Class Conversion May have array of base class pointers –can have them point to variety of derived class objects Problem : can access only base class functions Solution will be to use virtual functions and polymorphism in next chapter

38 Software Engineering with Inheritance Designers (or programmers of previous systems) provide base classes Client (or succeeding) programmer uses inheritance to make his/her version in a derived class –makes it specific for new application –source code of base class not needed, only.h and.obj files

39 Composition Vs. Inheritance Recall "is-a" relationship, –supported by public inheritance –savings acct object is a bank acct object Recall "has-a" relationship –hierarchical record structures –Bank-acct object has a telephone field or member, has a member number –This is an example of composition

40 Composition Vs. Inheritance Changes to a derived class do not require recompiling of the base class But Changes in structure of Telephone_num for Employee, require recompilation of code which uses Telephone

41 "Uses A" Relationship Classes may not have the "is-a" relationship but they may need to "be aware" of each other Person object may use a Car object A function uses an object by issuing a function call to a member function of that object

42 "Knows A" Relationship Example -- a Person object and a Car object cannot have an "is-a" relationship but... The Person object may "know of" Car object Accomplished by pointer members linking one type of object to another Sometimes called an "association"

43 Case Study: Point, Circle, Cylinder Author illustrates many points of the chapter Refer to figure 9.8 Listen to audio explanation on Text CD

44 Multiple Inheritance A class is derived from more than one base class Inherits members of several base classes Powerful tool but can cause some ambiguity problems Should be used when an "is-a" relationship exists between a new derived type and two or more existing base types Note figure 9.11 & audio description on Text CD

45 Multiple Inheritance Indicate multiple inheritance by following colon : inheritance indicator with comma separated list of base classes class Derived : public Base1, public Base2 {...

46 Multiple Inheritance Derived-class constructor calls each of base-class constructors –use member-initializer syntax –order is same as sequence of declaration Derived::Derived (int i, char c, double f) : Base1 (i), Base2(c), real (f) { }