1 / 30

Introduction to Inheritance

Introduction to Inheritance. Inheritance: 1 of 3 main features of OOP Form of software reusability (Derived) classes are created by absorbing the methods and variables of an existing (base) class It then adds its own methods to enhance its capabilities

coy
Download Presentation

Introduction to Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Inheritance • Inheritance: • 1 of 3 main features of OOP • Form of software reusability • (Derived) classes are created by absorbing the methods and variables of an existing (base) class • It then adds its own methods to enhance its capabilities • “Is a” relationship: derived class object can be treated as base class object • A derived class can only access non-private base class members unless it inherits accessor functions • Constructors are not inherited

  2. Two primary ways to use Inheritance • Extension (like you are doing in program 3b) • Reuse code written in base class • Add new methods that are not in base class • Call methods of base class to implement it • May or may not have access to member data of base class • Specialization • Derived class inherits all members of the base class • If method inherited operates as desired, no additional work required • If method does not operate as desired, override method

  3. Base Classes and Derived Classes • To specify that class one is derived from class two • class Two: public One • Examples: • class Circle : public Shape • class QATree : public Btree <string>

  4. Base Classes and Derived Classes CommunityMember Employee Student Alumnus Faculty Staff Administrator Teacher Inheritance forms a tree-like hierarchy Inheritance hierarchy for university CommunityMembers.

  5. access modifiers for class members • public members: • Can be accessed by base class or any class derived from that base class and the class’ s clients • private members: • Can be accessed by base class but not by any class derived from that base class • protected members • Can be accessed by base class or any class derived from that base class In general, a class’s data members should be private

  6. Overriding • A derived-class method nay override a base-class method • If a base class method is going to be overridden it must be declared virtual

  7. Relationship between Base Classes and Derived Classes • Example: • Create a class Point • Create a class circle • Create class Circle2 (which directly inherits from class Point) to show it cannot access private data members of Point • Create class Circle3 (which directly inherits from class Point) to show it can access protected data members of Point; and Circle3 is easier to maintain • Create class Circle4 (which directly inherits from class Point) to show how it can call public methods of class Point to access the private data members of Point

  8. NOTE • For convenience and brevity ONLY • I’m not creating .h and corresponding .cpp files. • I putting the code “inline” in the class declaration. • YOU ARE NOT ALLOWED TO DO THIS WITHOUT GETTING THE OK FROM YOUR INSTRUCTOR!

  9. X and Y coordinates, declared private so other classes cannot directly access them Default point constructor Constructor to set coordinates to parameters, //Point class represents an x-y coordinate pair. // Point class definition implicitly inherits class Point { // point coordinates private: int x, y; public: // default (no-argument) constructor Point() { x = 0; y = 0; } // parameterized constructor Point( intxValue, intyValue ) { x = xValue; y = yValue; }

  10. //accessor methods int GetX() { return x;} int GetY() { return Y; } //transformer methods int SetX(int newX) { x = newX; } int SetX(int newY) {y = newY; } // return string representation of Point virtual string ToString() { return"[" + str(x) + ", " + str(y) + "]"; } } // end class Point

  11. Create a Point object Change coordinates of Point object Calls the ToString method of class Point implicitly // PointTest.cpp // Testing class Point. // PointTest definition int main () { // instantiate Point object Point point (72, 115); // display point coordinates via X and Y properties string output = "X coordinate is " + str(point.GetX()) + "\n" + "Y coordinate is " + str(point.GetY()); point.SetX(10); // set x-coordinate via X property point.SetY (10); // set y-coordinate via Y property // display new point value cout << "\n\nThe new location of point is " ; cout << point.ToString(); system(“pause”); return 0; }

  12. Declare coordinates and radius of circle as private Circle constructors // Circle class definition implicitly inherits from Object class Circle { private: int x, y; // coordinates of Circle's center double radius; // Circle's radius public: // default constructor Circle() { x = 0; y = 0; radius = 0; } // constructor Circle( intxValue, intyValue, doubleradiusValue ) { x = xValue; y = yValue; Radius = radiusValue; } // Methods for GetX, GetY, GetRadius, SetX, SetY here Circle does NOT inherit from Point

  13. // calculate Circle diameter double Diameter() { return radius * 2; } // calculate Circle circumference double Circumference() { return Math.PI * Diameter(); } // calculate Circle area double Area() { return Math.PI * Math.Pow( radius, 2 ); } // return string representation of Circle string ToString() { return"Center = [" + str(x) + ", " + str(y) + "]" + "; Radius = " + str(radius); } } // end class Circle

  14. Create a Circle object Change coordinates and radius of Circle object Call to circle’s ToString method // Testing class Circle. int main ( ) { { // instantiate Circle Circle circle ( 37, 43, 2.5 ); // get Circle's initial x-y coordinates and radius cout << "X coordinate is " << circle.GetX() ; cout << "\nY coordinate is " + circle.GetY() << "\nRadius is “ ; cout << circleGet.Radius(); // set Circle's x-y coordinates and radius to new values circle.SetX(2); circle.SetY (2); circle.SetRadius (4.25); // display Circle's string representation cout << "\n\nThe new location and radius of " << "circle are \n" << circle.ToString() << "\n"; // display Circle's diameter cout << "Diameter is " << circle.Diameter() ) << "\n"; CircleTest.cs

  15. Call Circle’s Circumference and Area methods for output // display Circle's circumference cout <<"Circumference is " ; cout << circle.Circumference() << "\n"; // display Circle's area cout << "Area is " << String.Format( "{0:F}", circle.Area() ); } // end main

  16. Declare class Circle to derive from class Point Declare radius as private Calls to base class methods Attempt to directly change private base class members results in an error // Circle2 class definition inherits from Point class Circle2 : public Point { private: double radius; // Circle2's radius public: // default constructor Circle2() { radius = 0; SetX (0); SetY (0); } // constructor public Circle2 (int xValue, int yValue, double radiusValue ) { SetX (xValue); SetY (yValue); radius = radiusValue; } Circle2.cs Circle2 (directly inherits from class Point) but it cannot access private data members of Point

  17. Attempt to directly access private base class members results in an error // return string representation Circle string override ToString() { return"Center = [" + str (GetX()) + ", " + str (GetY()) + "]" + "; Radius = " + str (GetRadius()); } Circle2.cs + str (x) If you were to use str(x)

  18. Declare coordinates as protected so derived classes can directly access them // Point2 class contains an x-y coordinate pair as protected data. public class Point2 { // point coordinate protected: int x, y; public: // default (no-argument) constructor Point() { x = 0; y = 0; } // parameterized constructor Point( intxValue, intyValue ) { x = xValue; y = yValue; } // accessor and transformer methods here Point2.cs

  19. Class Circle3 inherits from Point2 Directly changing protected base class members does not result in error // Circle3 class definition inherits from Point2 class Circle3 : public Point2 { private: double radius; // Circle's radius // default constructor Circle3() { x = 0; y = 0; radius = 0; } // parameterized constructor Circle3( int xValue, int yValue, double radiusValue ) { // implicit call to Point constructor occurs here x = xValue; y = yValue; Radius = radiusValue; } // property Radius double GetRadius() { return radius; } Circle3 (directly inherits from class Point2) . Shorter than Circle – it inheritspublic properties X and Y. It can access protected data members of Point2 without error.

  20. Comments on Using protected • Derived class can modify protected base-class instance variables directly • Result in slight increase in performance (avoid overhead of a method call to a property's set or get method) • However, most applications, user interaction comprises large part of execution time • Creates two problems • Derived-class object does not have to use a method to set value of base-class’s protected data (so can leave object in inconsistent state) • Derived-class methods are now dependent on base-class implementation. If the base-class changes, derived-class must also be changed. BAD SOFTWARE ENGINEERING!!!

  21. Comments on Using protected • Use protected access when base-class provides service only to derived-classes (and not to any other class) • Better to include public or protected properties and methods that access private data

  22. Back to declaring coordinates as private. BETTER SOFTWARE ENGINEERING! // Point class definition implicitly inherits from Object class Point { // point coordinate private: int x, y; Point – no difference from earlier version of Point

  23. Constructor with call to base class default constructor Parameterized Constructor Call to base class parameterized constructor // Circle4 class definition inherits from Point class Circle4 : public Point { private: double radius; public: // default constructor Circle4() : Point () { radius = 0; } // parematerized constructor Circle4( int xValue, int yValue, double radiusValue ) : Point ( xValue, yValue ) { radius = radiusValue; } // accessor and transformer methods for radius • Circle4 (directly inherits from class Point) • It cannot access private data members of Point. • Invokes non-private base-class methods and • properties to access the private data members

  24. Method Area declared virtual so it can be overridden Circle4’s ToString method overrides Point’s ToString method Call Point’s ToString method to display coordinates // calculate Circle diameter double Diameter() { return radius * 2; // use property Radius } // calculate Circle circumference double Circumference() { return Math.PI * Diameter(); } // calculate Circle area virtual double Area() { return Math.PI * Math.Pow( radius, 2 ); // use property } // return string representation of Circle4 virtual string ToString() { // use base reference to return Point string representation return"Center= " + Point.ToString() + "; Radius = " + str(radius); } } // end class Circle4 Circle4.cs

  25. Change coordinates and radius of Circle4 object Create new Circle4 object Implicit call to Circle4’s ToString method // main entry point for application int main() { // instantiate Circle4 Circle4 circle ( 37, 43, 2.5 ); // get Circle4's initial x-y coordinates and radius cout << "X coordinate is " << circle.GetX() << "\n" ; cout << "Y coordinate is " << circle.GetY() << "\n" ; cout << "Radius is " << circle.GetRadius(); // set Circle4's x-y coordinates and radius to new values circle.SetX (2); circle.SetY(2); circle.SetRadius (4.25); // display Circle4's string representation cout << "\n\nThe new location and radius of circle are " ; cout << "\n" + circle.ToString() << "\n"; // display Circle4's Diameter cout << "Diameter is " << circle.Diameter() ) << "\n";

  26. Comments on Last Example • Overriding derived-class method often calls the base-class version to do additional work • Circle4’s ToString calling base class Point’s ToString • Failure to use base reference infinite recursion • Chain base references to several levels of hierarchy • A redefinition in a derived-class of a base-class method that uses a different signature than that of base-class method is method overloading, NOT method overriding. • NOTE: Everyone in Java and C#.NET community includes a method called ToString to provide an object’s string representation.

  27. Case Study: Three-Level Inheritance Hierarchy • The first thing a derived class does is call its base class’ constructor, either explicitly or implicitly • Three-level inheritance example: • Class Cylinder inherits from class Circle4 • Class Circle4 inherits from class Point

  28. Constructors and Destructors in Derived Classes • Instantiating a derived class causes base class constructor to be called, implicitly or explicitly • Can cause chain reaction when a base class is also a derived class • When a destructor is called, it performs its task and then invokes the derived class’ base class constructor Point constructor: Center = [72, 29]; Radius = 0 Circle4 constructor: Center = [72, 29]; Radius = 4.5 Point constructor: Center = [5, 5]; Radius = 0 Circle4 constructor: Center = [5, 5]; Radius = 10 Circle4 destructor: Center = [5, 5]; Radius = 10 Point destructor: Center = [5, 5]; Radius = 10 Circle4 destructor: Center = [72, 29]; Radius = 4.5 Point destructor: Center = [72, 29]; Radius = 4.5

  29. Software Engineering with Inheritance • Can customize derived classes to meet needs by: • Creating new member variables (eg. radius) • Creating new methods (eg. Diameter) • Override base-class methods (eg. ToString)

  30. Other OOP stuff • Interfaces • Abstract classes • Casting issues • Multiple and restricted inheritance

More Related