TCP1201 OOPDS 1 Inheritance. 2 Learning Objectives To understand inheritance terminology To understand multiple inheritance To understand diamond inheritance.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

INHERITANCE BASICS Reusability is achieved by INHERITANCE
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
LOGO Lecturer: Abdullahi Salad Abdi May 1, Object Oriented Programming in C++
Class Hierarchy (Inheritance)
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance and Polymorphism CS180 Fall Definitions Inheritance – object oriented way to form new classes from pre-existing ones –Superclass The.
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
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.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Inheritance. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
CSCI 143 OOP – Inheritance 1. What is Inheritance? A form of software reuse Create a new class from an existing class – Absorb existing class data and.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Inheritance and Polymorphism Recitation 04/10/2009 CS 180 Department of Computer Science, Purdue University.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Modelling classes Drawing a Class Diagram. Class diagram First pick the classes –Choose relevant nouns, which have attributes and operations. Find the.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
LECTURE 07 Programming using C# Inheritance
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Chapter 8 More Object Concepts
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
What is inheritance? It is the ability to create a new class from an existing class.
TCP1201 OOPDS Lecture 4 1. Learning Objectives  To understand upcasting & downcasting  To understand static polymorphism and dynamic polymorphism 
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
C# F 1 CSC 298 Object Oriented Programming (Part 1)
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
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.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Chapter 10 Inheritance and Polymorphism
Peyman Dodangeh Sharif University of Technology Fall 2014.
Object-Oriented Programming in C++ More examples of Association.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Chapter 8 Inheritance Part 1. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
November 27, 2001Lecture 231  Previous Lecture: Parameter passing Method overloading  Today’s Lecture: Introduction to inheritance Class diagrams and.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
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.
© 2004 Pearson Addison-Wesley. All rights reserved November 14, 2007 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL.
MAITRAYEE MUKERJI Object Oriented Programming in C++: Hierarchy / Inheritance.
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
A First Book of C++ Chapter 12 Extending Your Classes.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Advanced Programming in Java
Advanced Programming in Java
Inheritance.
Week 8 Lecture -3 Inheritance and Polymorphism
CSC 143 Inheritance.
Lecture 22 Inheritance Richard Gesick.
Advanced Programming Behnam Hatami Fall 2017.
Java Programming, Second Edition
Inheritance.
Method Overriding and method Overloading
Programming in C# CHAPTER 5 & 6
Presentation transcript:

TCP1201 OOPDS 1 Inheritance

2 Learning Objectives To understand inheritance terminology To understand multiple inheritance To understand diamond inheritance and virtual inheritance To understand protected access privilege To understand the call order of constructor and destructor in inheritance To understand function overriding

TCP1201 OOPDS 3 Inheritance By nature we commonly group objects that have a common attributes and behaviors into classes (categories)., e.g. animals, vehicles, and human. Under each of these classes there can be 0, 1, or more subclasses (subcategories).

TCP1201 OOPDS 4 Example 1/2 Under the animal class, we can create three subclasses: bird, mammal and fish. Animal, bird, mammal and fish are classes. Bird, mammal and fish are subclasses of animal. Eagle, parrot, whale, monkey, goldfish and shark are instances/objects. (They can actually be sub-subclasses.)

TCP1201 OOPDS 55 The "is-a" Relationship Note the following statements: –Eagle is a bird. Parrot is a bird. Both are also animals. –Cat is a mammal. Monkey is a mammal. Both are also animals. –Goldfish is a fish. Shark is a fish. Both are also animals. A bird is different from a mammal, a mammal is different from a fish, and a fish is different from a bird. Even though they are all different among one another, they are the same in regard that they are all animals.

TCP1201 OOPDS 66 Example 2/2 Under the Human class, we can create 2 subclasses: Lecturer and Student. Sharaf and Manoj are instances of Lecturer. Tom and John are instances of Student. Sharaf, Manoj, Tom and John are also Humans.

TCP1201 OOPDS 77 Inheritance Terminology The "is-a" relationship between a superclass and its subclasses is commonly referred to as inheritance. We say that a subclass "inherits from"/"derives from" a superclass. Example: Bird inherits from Animal. Subclass inherits all the characteristics (attributes and methods) from its superclass. –All objects of Bird have a common set of attributes and methods of Bird, and also inherit a common set of attributes and behaviors from Animal. –Example: If animals have skin, then birds also have skin. Inheritance promotes code reuse and simplifies code maintenance in the long run.

TCP1201 OOPDS 88 Definition of Inheritance Inheritance is the mechanism which allows a class B to inherit attributes and methods of a class A. We say "B inherits from A". Objects of class B have direct access to non-private attributes and methods of class A. If class B inherits from class A, then A is called the superclass/base class/parent class) of B. B is called the subclass/derived class/child class) of A. Superclass is more general than subclass –Subclass is more specific than superclass Superclass/ Base class/ Parent class Subclass/ Derived class/ Child class Is-a

TCP1201 OOPDS 99 Inheritance in UML Class Diagram From the following UML Class Diagram –We know that Human is the superclass. –Lecturer and Student are subclasses of Human class.

TCP1201 OOPDS The C++ Definition for the superclass Human: class Human { string name; public: Human(string name) : name(name) {} void speak(string sentence) { cout << "My name is " << name << ". " << sentence << endl; } }; 10 Superclass: Human

TCP1201 OOPDS 11 Defining Subclasses To indicate that a subclass inherits from superclass, we use a single colon ":", followed by an access privilege keyword (usually public ) and the name of the superclass in the declaration. class subclass : public superclass : {... }; In most cases, subclass' constructor should initialize superclass' attributes.

TCP1201 OOPDS 12 Subclass Lecturer Hence, the declaration for Lecturer is as follows: class Lecturer : public Human { string room; public: Lecturer (string name, // 'name' is for initializing // superclass' attribute. string room); };

TCP1201 OOPDS 13 Initializing Superclass from Subclass Wrong way of initializing superclass from subclass: Lecturer (string name, string room) { this->name = name; // Compile-error. this->room = room; } or Lecturer (string name, string room) : name(name), room(room) {} // Compile-error. The reason is name is a private attribute of superclass hence cannot be directly accessed by subclass.

TCP1201 OOPDS 14 Calling Superclass Constructor The correct way of initializing superclass is to invoke superclass constructor at subclass' constructor initializer list. Lecturer (string name, string room) : Human(name) { // Correct. this->room = room; } "calls" the Human constructor with the argument name. Note that we are reusing existing code (Human constructor). or Lecturer (string name, string room) : Human(name), room(room) { } // Correct.

TCP1201 OOPDS Inheritance Example class Human { string name; public: Human (string name) : name(name) {} void speak (string sentence) { cout << "My name is " << name << ". " << sentence << endl; } }; class Lecturer : public Human { string room; public: Lecturer (string name, string room) : Human(name), room(room) {} }; class Student : public Human { double CGPA; public: Student (string name, double CGPA) : Human(name), CGPA(CGPA) {} }; 15 Output: My name is Hugo. Ha My name is Lee. Hi My name is Sarah. Ho int main() { Human h("Hugo"); Lecturer l("Lee", "BR1111"); Student* s = new Student ("Sarah", 3.99); h.speak ("Ha"); l.speak ("Hi"); // Human::speak() s->speak ("Ho");// Human::speak() delete s; }

TCP1201 OOPDS Now assume that both Lecturer and Student need a new attribute called address. Instead of adding the address at subclasses Lecturer and Student directly, we should add the address at superclass Human because the attribute will be inherited by both Lecturer and Student. The C++ Definition for the superclass Human: class Human { string name; string address; public: Human(string name, string address = "") : name(name), address(address) {} Simpler Code Maintenance

TCP1201 OOPDS 17 Multiple Levels of Inheritance We can have more than one level of inheritance. For example, the Student class can be the superclass of LocalStudent and ForeignStudent. (Ignore the attribute address we discuss in previous slide.)

TCP1201 OOPDS 18 Multiple Levels of Inheritance A subclass inherits the attributes and methods of all of its superclasses: –A ForeignStudent object will, therefore, inherit: all of the attributes and methods of Human class, plus the attributes and methods of Student class, plus the attributes and methods of ForeignStudent class.

TCP1201 OOPDS 19 Multiple Levels of Inheritance A subclass constructor can invoke only the immediate superclass constructor, not the super-superclass constructor, unless virtual inheritance is used. class LocalStudent : public Student { string icno; public: LocalStudent (string name, double CGPA, string icno) : Human(name), // Compile error, attempt to call // super-superclass constructor. Student(name, CGPA), icno(icno) {} };

TCP1201 OOPDS 20 Multiple Levels of Inheritance Sample constructor for LocalStudent and ForeignStudent. class LocalStudent : public Student { string icno; public: LocalStudent (string name, double CGPA, string icno) : Student(name, CGPA), // Call immediate superclass constructor, okay icno(icno) {} }; class ForeignStudent : public Student { string passportno; public: ForeignStudent (string name, double CGPA, string passportno) : Student(name, CGPA), passportno(passportno) {} // okay };

TCP1201 OOPDS 21 Multiple Inheritance Multiple inheritance is NOT the same as "multiple levels of Inheritance". Multiple inheritance occurs when a class has 2 or more direct/immediate superclasses. Use comma "," to separate superclasses. class C : public A, public B { public: C(…) : A(…), B(…) // Constructor initialization list. {} }; AB C Constructor for class A Constructor for class B

TCP1201 OOPDS 22 Diamond Inheritance Problem A C B1 B2 Multiple inheritance may introduce diamond inheritance problem, which arises when 2 classes B1 and B2 inherit from A, and class C inherits from both B1 and B2. The problem is C would have duplicate sets (2 sets) of the members inherited from A, which might not be desirable. If one set of members of A is preferred at C, we can use virtual inheritance to avoid duplicate sets.

TCP1201 OOPDS 23 Diamond Inheritance Problem class A {... }; class B1: public A {... }; class B2: public A {... }; class C: public B1, public B2 { public: C(...) : B1(...), B2 (...) { } }; Solution: virtual inheritance class A {}; class B1: virtual public A {}; class B2: virtual public A {}; class C: public B1, public B2 { public: C(...) : A(...), B1(...), B2 (...) {} // Must call super-superclass constructor. }; Virtual Inheritance A B1 C B2

TCP1201 OOPDS 24 protected Access Privilege Recall from the previous lecture the following classes: class Human { string name; // private... }; class Lecturer : public Human { string room; public: Lecturer (string name, string room) : Human(name), room(room) {} // 'name' is private in Human... }; The reason we have to initialize the attribute name via constructor initialization list is subclass cannot access superclass' private members.

TCP1201 OOPDS 25 protected Access Privilege If a class member is declared as protected, then it is accessible to the class itself and its subclasses. class Human { protected: string name;... }; class Lecturer : public Human { string room; public: Lecturer (string name, string room) { this->name = name; // Fine since 'name' is protected.... };

TCP1201 OOPDS 26 protected Access Privilege However, same as private member, a protected member of a superclass is not accessible at subclass' constructor initilizer list. class Human { protected: string name;... }; class Lecturer : public Human { string room; public: Lecturer (string name, string room) { : name(name), // Error, 'name' is not accessible here. room(room) { }... };

TCP1201 OOPDS 27 protected Access Privilege We use hash symbol "#" to denote protected access privilege in UML Class Diagram. Human # name: string + Human (name: string) + speak (sentence: string): void

TCP1201 OOPDS 28 Accessing Superclass' Private Attribute Subclass can access/modify superclass' private attributes indirectly via the public/protected get/set methods provided by superclass. class Super { int z; public: void setZ (int z) { this->z = z; } int getZ() { return z; } }; class Sub: public Super { public: Sub(int z) { setZ (z); // superclass' setZ } }; int main() { Sub s(3); cout << s.getZ() << endl; s.setZ (33); // Fine cout << s.getZ() << endl; } Output: 3 33

TCP1201 OOPDS Function Overriding A subclass can override a superclass method by supplying a new version of that method with the same signature. When the method is invoked in the subclass, the subclass version is automatically selected. class Human { public: void eat() { cout << "Eating\n"; } void speak() { cout << "I'm a human\n"; } }; class Student : public Human { public: void speak() { // Override superclass' speak(). cout << "I'm a student\n"; } };

TCP1201 OOPDS 30 Function Overriding class Human { public: void eat() { cout << "Eating\n"; } void speak() { cout << "I'm a human\n"; } }; class Student : public Human { public: void speak() { // Override superclass' speak(). cout << "I'm a student\n"; } }; int main() { Human* h = new Human; Student* s = new Student; h->speak(); // call Human::speak() s->speak(); // call Student::speak() h->eat(); // call Human::eat() s->eat(); // call Human::eat() delete h; delete s; } Output: I'm a human I'm a student Eating