Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 1 Generalization versus Abstraction.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CMSC 202 Inheritance. Aug 6, Object Relationships An object can have another object as one of instance variables. The Person class had two Date.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
ITEC200 – Week03 Inheritance and Class Hierarchies.
Object-Oriented PHP (1)
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.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Inheritance and Polymorphism CS351 – Programming Paradigms.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Designing Classes OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 1 Designing the Classes Once.
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
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.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
OBJECT ORIENTED PROGRAMMING CONCEPTS ISC 560. Object-oriented Concepts  Objects – things names with nouns  Classes – classifications (groups) of similar.
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
Intro to OOP with Java, C. Thomas Wu
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Lecture 10 Inheritance “Absolute C++” Chapter 14.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
 2002 Prentice Hall. All rights reserved. 1 Introduction to Inheritance Inheritance: –1 of 3 main features of OOP –Form of software reusability –(Derived)
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Inheritence Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September.
C# F 1 CSC 298 Object Oriented Programming (Part 1)
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Object Oriented Software Development
Polymorphism OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 1 Definition polymorphismthe ability.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Communication OO Software Design and Construction Computer Science Dept Va Tech February 2001 ©2001 McQuain WD & Keller BJ 1 Communicating Objects Think.
Programming Fundamentals1 Chapter 8 OBJECT MANIPULATION - INHERITANCE.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
C++ Inheritance Data Structures & OO Development I 1 Computer Science Dept Va Tech June 2007 © McQuain Generalization versus Abstraction Abstraction:simplify.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
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.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Polymorphism Data Structures & OO Development I 1 Computer Science Dept Va Tech May 2006 ©2006 McQuain & Ribbens Definition polymorphismthe ability to.
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
CMSC 202 Polymorphism.
Inheritance and Polymorphism
Understanding Inheritance
Introduction to Classes
Extending Classes.
Java Programming Language
Derived Classes in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Object-Oriented PHP (1)
Final and Abstract Classes
Programming in C# CHAPTER 5 & 6
Presentation transcript:

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 1 Generalization versus Abstraction Abstraction:simplify the description of something to those aspects that are relevant to the problem at hand. Generalization:find and exploit the common properties in a set of abstractions. hierarchy polymorphism genericity patterns

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 2 Four-Fold Path to Generalization Hierarchy Exploitation of an “is-a-kind-of” relationship among kinds of entities to allow related kinds to share properties and implementation. Polymorphism Exploitation of logical or structural similarities of organization to allow related kinds to exhibit similar behaviors via similar interfaces. Genericity Exploitation of logical or structural similarities of organization to produce generic objects. Patterns Exploitation of common relationship scenarios among objects. (e.g., client/server system)

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 3 Hierarchy Represented by generalize/specialize graph Based on “is-a-kind-of” relationship E.g., a Manager is an Employee; a robin is a bird, and so is an ostrich. Is a form of knowledge representation – a “taxonomy” structures knowledge about nearby entities. Extendable without redefining everything E.g., knowing a robin is a bird tells me that a robin has certain properties and behaviors, assuming I know what a “bird” is. Specialization can be added to proper subset of hierarchy

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 4 Taxonomy A generalization/specialization hierarchy based on “is-a-kind-of” relationships: Person Name Address Employee Name Address ID Department Student Name Address ID Major Level more general less details more specialized more details

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 5 Inheritance Terminology – Base type or class (a.k.a. superclass, parent type) – Derived type or class (a.k.a. subclass, subtype, child type) Important Aspects – Programming: implement efficiently a set of related classes (mechanical) – Design: organize coherently the concepts in an application domain (conceptual) – Software Engineering: design for flexibility and extensibility in software systems (logical)

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 6 Student Class w/o Inheritance class Student { private: Name Nom; Address Addr; string Major; string ID; int Level; public: Student(const Name& N, const Address& A, string M = "US", string I = " ", int L = 10); Name getName() const; Student& setName(const Name& N); //... string getMajor() const; Student& setMajor(const string& D); string getID() const; Student& setID(const string& I); int getLevel() const; Student& setLevel(int L); ~Student(); }; Specify all the data members Specify appropriate constructors Specify accessors and mutators for all data members

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 7 Employee Class w/o Inheritance class Employee { private: Name Nom; Address Addr; string Dept; string ID; public: Employee(const Name& N, const Address& A, string D = "", string I = ""); Name getName() const; Employee& setName(const Name& N); //... string getDept() const; Employee& setDept(const string& D); string getID() const; Employee& setID(const string& I); ~Employee(); }; Specify all the data members Specify appropriate constructors Specify accessors and mutators for all data members

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 8 What is Common? Both classes contain the data members Name Nom; Address Addr; string ID; and the associated member functions Name getName() const; Address getAddress() const; string getID() const; void setName(const Name& N); void setAddress (const Address& A); void setID(const string& I); From a coding perspective, this is somewhat wasteful because we must duplicate the declarations and implementations in each class. From a S/E perspective, this is undesirable since we must effectively maintain two copies of (logically) identical code.

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 9 What Do We Want? Simply put, we want to exploit the fact that Student and Employee both are "people". That is, each shares certain data and function members which logically belong to a more general (more basic) type which we will call a Person. We would prefer to NOT duplicate implementation but rather to specify that each of the more specific types will automatically have certain features (data and functions) that are derived from (or inherited from) the general type. Question: are there any attributes or operations in the overlap that we don't want to include in the base type Person ?

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 10 How Do We Get It? By employing the C++ inheritance mechanism… Inheritance in C++ is NOT simple, either syntactically or semantically. We will examine a simple case first (based on the previous discussion) and defer explicit coverage of many specifics until later. Inheritance in C++ involves specifying in the declaration of one class that it is derived from (or inherits from) another class. Inheritance may be public or private (or protected). At this time we will consider only public inheritance. It is also possible for a class to be derived from more than one (unrelated) base class. Such multiple inheritance will be discussed later…

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 11 The Base Class: Person class Person { private: Name Nom; Address Addr; public: Person(const Name& N = Name(), const Address& A = Address()); Name getName() const; Person& setName(const Name& N); Person& setAddress(const Address& A); Address getAddress() const; ~Person(); }; Having identified the common elements shared by both classes ( Employee and Student ), we specify a suitable base class: The base class should contain data members and function members that are general to all the types we will derive from the base class.

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 12 A Derived Class: Employee class Employee : public Person { private: string Dept; string ID; public: Employee(); Employee(const Person& P, const string& D, const string& I); Employee(const Name& N, const Address& A, const string& D, const string& I); string getDept() const; Employee& setDept(const string& D); string getID() const; Employee& setID(const string& I); ~Employee(); }; Specify base classSpecify public inheritance Specify additional data members not present in base class Specify appropriate constructors Specify accessors and mutators only for the added data members

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 13 Logical View of an Employee Object Public interfacePrivate members Nom Addr Dept ID Employee(...) getDept( ) getAddress( ) Employee “layer” Person “layer” (inherited from base type) public members of the base type are public in the derived type private members of the base type are private in the derived type

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 14 Constructing a Derived Type Object Employee::Employee() : Person() { Dept = "None"; ID = "None"; } When an object of a derived type is declared, the default constructor for the base type will be invoked BEFORE the body of the constructor for the derived type is executed (unless an alternative action is specified…). It's not necessary to explicitly invoke the base constructor here, but it makes the behavior more obvious. Alternatively, the derived type constructor may explicitly invoke a non-default base type constructor: Employee::Employee(const Person& P, const string& D, const string& I) : Person(P) { Dept = D; ID = I; } Here, the (default) copy constructor for the base class is used.

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 15 Derived Class Member Access Problem Employee::Employee(const Person& P, const string& D, const string& I) { Nom = P.getName(); Addr = P.getAddress(); Dept = D; ID = I; } Error: cannot access private member declared in class Person. Objects of a derived type inherit the data members and function members of the base type. However, the derived object may not directly access the private members of the base type: Employee::Employee(const Person& P, const string& D, const string& I) { setName(P.getName()); setAddress(P.getAddress()); //... } For a derived-class constructor we directly invoke a base class constructor, as shown on the previous slide, or use the Person interface:

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 16 Protected Access The restriction on a derived type's access seems to pose a dilemma: -Having the base type use only public members is certainly unacceptable. -Having the derived class use the public interface of the base class to access and/or modify private base class data members is clumsy. class Person { protected: Name Nom; Address Addr; public: //... }; Employee::Employee( /*...*/ ) { Nom = N; // OK now Addr = A; Dept = D; ID = I; } C++ provides a middle-ground level of access control that allows derived types to access base members which are still restricted from access by unrelated types. The keyword protected may be used to specify the access restrictions for a class member:

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 17 A Sibling Class class Student : public Person { private: string Major; string ID; int Level; public: Student(const Person& P = Person(), const string& M = "None", const string& I = " ", int L = 10); string getMajor() const; Student& setMajor(const string& D); string getID() const; Student& setID(const string& I); int getLevel() const; Student& setLevel(int L); ~Student(); }; Note that, so far as the language is concerned, Student and Employee enjoy no special relationship as a result of sharing the same base class.

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 18 Using Objects of Derived Classes //... Person JBH(Name("Joe", "Bob", "Hokie"), Address("Oak Bridge Apts", "#13", "Blacksburg", "Virginia", "24060")); Employee JoeBob(JBH, "Sales", "jbhokie"); cout << "Name: " << JoeBob.getName().formattedName() << endl << "Dept: " << JoeBob.getDept() << endl << "ID: " << JoeBob.getID() << endl; Person HHooIV(Name("Haskell", "Horatio", "Hoo"), Address("1 Rotunda Circle", "", "Charlottesville", "VA", "21009")); Student HaskellHoo(HHooIV, "Undecided", " ", 40); HaskellHoo.setAddress(Address("Deke House", "333 Coors Way", "Charlottesville", "VA", "21010")); HaskellHoo.setMajor("Undeclared"); //... Base object is only declared to simplify constructor call. Objects of a derived class may be declared and used in the usual way: Call base member Call derived members …to the user there's no evidence here that the class is derived…

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 19 Extending the Hierarchy There's no restriction on how many levels of inheritance can be designed, nor is there any reason we can't mix inheritance with association and/or aggregation. Actually, Employee is not a terribly interesting class but it has two (or more) useful sub-types: Person StudentEmployee StaffProfessor Address Name

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 20 Staff Class and Professor Class For the sake of an example, a staff member is paid an hourly wage, so the class Staff must provide the appropriate extensions… class Staff : public Employee { private: double HourlyRate; public: Staff(const Employee& E, double R = 0.0); double getRate() const; void setRate(double R); double grossPay(int Hours) const; ~Staff(); }; class Professor : public Employee { private: double Salary; public: Professor(const Employee& E, double S = 0.0); double getSalary() const; void setSalary(double S); double grossPay(int Days) const; ~Professor(); }; …whereas a professor is paid a fixed salary:

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 21 An Inadequate Base Class Member Function Employee& Employee::setID(const string& S) { ID = S; return (*this); }; The base member function Employee::setID() is simple: This implementation raises two issues we should consider: -What if there's a specialized way to set the ID field for a derived type? -Is the return type really acceptable for a derived type? We’ll consider the first question now… suppose that the ID for a professor must begin with the first character of that person's department. Then Professor::setID() must enforce that restriction.

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 22 Overriding a Base Class Member Function Professor& Professor::setID(const string& I) { if (I[0] == Dept[0]) ID = I; else ID = Dept[0] + I; return (*this); }; In the derived class, provide an appropriate implementation, using the same interface. That will override the base class version when invoked on an object of the derived type: The appropriate member function implementation is chosen (at compile time), based upon the type of the invoking object and the inheritance hierarchy. Beginning with the derived class, the hierarchy is searched upward until a matching function definition is found: Employee E( /*...*/ ); Professor F(/*...*/ ); //... E.setID("12334"); // Employee::setID() F.setID("99012"); // Professor::setID() Assuming that Dept has protected status.

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 23 Extending a Base Class Member Function void Person::Display(ostream& Out) { Out << "Name: " << Name << endl << "Address: " << Address; }; Suppose we added a display member function to the base type: This is inadequate for a Professor object since it doesn't recognize the additional data members… we can fix that by overriding again (with a twist): void Professor::Display(ostream& Out) { Person::Display(Out); Out << "ID: " << ID << endl << "Dept: " << Department; }; Here, we use the base class display function, invoking it with the appropriate scope resolution, and then extend that implementation with the necessary additional code.

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 24 Copying a Derived Object to a Base Object Employee eHomer(Name("Homer", "P", "Simpson"), Address("1 Chernenko Way", "", "Blacksburg", "VA", "24060"), "Physics", "P401" ); Professor Homer(eHomer, ); Employee E; Person P; E = Homer; // legal assignments, but usually inadvisable P = Homer; It is legal to assign a derived type object to a base type object: Salary Dept ID Nom Addr Dept ID Nom Addr Nom Addr Homer E P When a derived object is assigned to a base target, only the data and function members appropriate to the target type are copied. This is known as slicing.

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 25 Another Slice void PrintEmployee(Employee toPrint, ostream& Out) { Out << toPrint.getID(); Out << '\t'; Out << toPrint.getName(); Out << '\n'; } PrintEmployee() sees only the Employee layer of the actual parameter that was passed to it by value. That's actually OK in this case since that's all PrintEmployee() deals with anyway. However, it's certainly a limitation you must be aware of… what if you wanted to write a generic print function that would accept any derived type, without slicing?

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 26 Assigning Base Type to Derived Type // assume declarations from slide Homer = eHomer; // illegal – compile time error By default, a base type object may not be assigned to a derived type object: Name:... Addr:... Dept: Physic ID: P401 Salary: HomereHomer Name:... Addr:... Dept: Physics ID: P401 … some sort of action must be taken with respect to the derived type data members that have no analogs in the base type. It's possible to legalize this with the right overloading (later), but… ??

Inheritance OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 27 Parameter Passing Issues The rules are essentially the same in four situations: -when passing a derived object by value as a parameter. -when returning a derived object by value -when initializing a base object with a derived object -when assigning a derived object to a base object A derived type may be copied when a base type is targeted — however, slicing will occur. A base type may not be copied when a derived type is targeted — unless a suitable derived type constructor is provided to legalize the conversion.