Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object-Oriented Programming: Inheritance

Similar presentations


Presentation on theme: "Object-Oriented Programming: Inheritance"— Presentation transcript:

1 Object-Oriented Programming: Inheritance
10 Object-Oriented Programming: Inheritance

2 Good as it is to inherit a library, it is better to collect one.
Say not you know another entirely, till you have divided a inheritance with him. Johann Kasper Lavater This method is to define as the number of a class the class of all classes similar to the given class. Bertrand Russell Good as it is to inherit a library, it is better to collect one. Augustine Birrell Save base authority from others’ books. William Shakespeare

3 OBJECTIVES In this chapter you will learn:
What inheritance is and how it promotes software reusability. The notions of base classes and derived classes. To use keyword Inherits to create a class that inherits attributes and behaviors from another class. To use the access modifier Protected in a base class to give derived class methods access to base class members. To access base class members from a derived class with MyBase. How constructors are used in inheritance hierarchies. To access the current object with Me and MyClass. The methods of class Object—the direct or indirect base class of all classes in Visual Basic.

4 10.1 Introduction 10.2 Base Classes and Derived Classes 10.3 Protected Members 10.4 Relationship between Base Classes and Derived Classes Creating and Using a CommissionEmployee Class Creating a BasePlusCommissionEmployee Class without Using Inheritance Creating a CommissionEmployee– BasePlusCommission Employee Inheritance Hierarchy CommissionEmployee–BasePlusCommissionEmployee Inheritance Hierarchy Using Protected Instance Variables CommissionEmployee–BasePlusCommissionEmployee Inheritance Hierarchy Using Private Instance Variables

5 10.5 Constructors in Derived Classes
10.6 Software Engineering with Inheritance 10.7 Class Object 10.8 Friend Members 10.9 Wrap-Up

6 10.1 Introduction Inheritance Software reusability
Create new class from existing class Absorb existing class’s data and behaviors Enhance with new capabilities Derived class extends base class Derived class More specialized group of objects Behaviors inherited from base class Can customize Additional behaviors

7 10.1 Introduction (Cont.) Class hierarchy Direct base class
Inherited explicitly (one level up hierarchy) Indirect base class Inherited two or more levels up hierarchy Single inheritance Inherits from one base class Multiple inheritance Inherits from multiple base classes Visual Basic does not support multiple inheritance

8 10.2 Base Classes and Derived Classes
Object of one class “is an” object of another class Example: Rectangle is a quadrilateral. Class Rectangle inherits from class Quadrilateral Quadrilateral: base class Rectangle: derived class Base class typically represents larger set of objects than derived classes Example: Base class: Vehicle Cars, trucks, boats, bicycles, … Derived class: Car Smaller, more-specific subset of vehicles

9 Fig. 10.1 | Inheritance examples.

10 10.2 Base Classes and Derived Classes (Cont.)
Inheritance hierarchy Inheritance relationships: tree-like hierarchy structure Each class becomes Base class Supply members to other classes OR Derived class Inherit members from other classes

11 Fig. 10.2 | Inheritance hierarchy for university CommunityMembers.

12 Fig. 10.3 | Inheritance hierarchy for Shapes.

13 10.3 Protected Members Protected access
Intermediate level of protection between Public and Private Protected members accessible by Base class members Derived class members Derived class access to base class member Keyword MyBase and a dot (.)

14 Software Engineering Observation 10.1
Derived class methods cannot directly access Private members of their base class. A derived class can change the state of Private base class instance variables only through non-Private methods provided in the base class and inherited by the derived class.

15 Software Engineering Observation 10.2
Declaring Private instance variables helps programmers test, debug and correctly modify systems. If a derived class could access its base class’s Private instance variables, classes that inherit from that derived class could access the instance variables as well. This would propagate access to what should be Private instance variables, and the benefits of information hiding would be lost.

16 10.4 Relationship between Base Classes and Derived Classes
Base class and derived class relationship Example: CommissionEmployee/BasePlusCommissionEmployee inheritance hierarchy CommissionEmployee First name, last name, SSN, commission rate, gross sale amount BasePlusCommissionEmployee Base salary

17 10.4.1 Creating and Using a CommissionEmployee Class
Class CommissionEmployee Extends class Object Inherits Every class in Visual Basic extends an existing class Except object Every class inherits object’s methods New class implicitly extends object To override base class method use keyword Overrides with the same signature (Overridden method must be declared Overridable) Constructors are not inherited The first task of any derived class constructor is to call its direct base class’s constructor

18 Outline Class CommissionEmployee Inherits class Object
Declare Private instance variables Commmission Employee.vb (1 of 4 ) Implicit call to object constructor Initialize instance variables Invoke properties GrossSales and CommissionRate to validate data

19 Outline Commmission Employee.vb (2 of 4 )

20 Outline Commmission Employee.vb (3 of 4 ) Validation

21 Outline Validation (4 of 4 ) Calculate earnings
Commmission Employee.vb (4 of 4 ) Calculate earnings Override method ToString of class Object

22 Common Programming Error 10.1
It is a compilation error to attempt to override a method that is not declared Overridable.

23 Common Programming Error 10.2
It is a compilation error to override a method with a method that has a different access modifier than the method being overridden.

24 Outline Instantiate CommissionEmployee object (1 of 2 )
Commission EmployeeTest.vb (1 of 2 ) Use CommissionEmployee’s properties to retrieve and change the object’s instance variable values Explicit call the object’s ToString method

25 Outline Explicit call the object’s CalculateEarnings method (2 of 2 )
Commission EmployeeTest.vb (2 of 2 ) Explicit call the object’s CalculateEarnings method

26 10.4.2 Creating a BasePlusCommissionEmployee Class without Using Inheritance
Class BasePlusCommissionEmployee Much of the code is similar to CommissionEmployee Private instance variables Public methods Constructor Properties Additions Private instance variable baseSalaryValue BaseSalary property

27 Outline Add instance variable baseSalary (1 of 5 )
BasePlus Commission Employee.vb (1 of 5 ) Use property BaseSalary to validate data

28 Outline BasePlus Commission Employee.vb (2 of 5 )

29 Outline BasePlus Commission Employee.vb (3 of 5 )

30 Outline Validates data and sets instance variable baseSalaryValue
BasePlus Commission Employee.vb (4 of 5 ) Update method CalculateEarnings to calculate the earnings of a base-salaried commission employee

31 Outline (5 of 5 ) Update method ToString to display base salary
BasePlus Commission Employee.vb (5 of 5 ) Update method ToString to display base salary

32 Outline Instantiate BasePlusCommissionEmployee object (1 of 2 )
BasePlus Commission EmployeeTest.vb (1 of 2 ) Use BasePluCommissionEmployee’s properties to retrieve and change the object’s instance variable values Explicitly call the object’s ToString method

33 Outline (2 of 2 ) Call the object’s CalculateEarnings method
BasePlus Commission EmployeeTest.vb (2 of 2 )

34 Software Engineering Observation 10.3
Copying and pasting code from one class to another can spread errors among multiple source code files. To avoid duplicating code (and possibly errors), use inheritance, rather than the “copy-and-paste” approach, where you want one class to “absorb” the members of another class.

35 Software Engineering Observation 10.4
With inheritance, the common instance variables and methods of all the classes in the hierarchy are declared in a base class. When changes are required for these common features, software developers need to make the changes only in the base class—derived classes then inherit the changes. Without inheritance, the changes would need to be made to all the source code files that contain copies of the code in question.

36 10.4.3 Creating a CommissionEmployee-BasePlusCommiionEmployee Inheritance Hierarchy
Class BasePlusCommissionEmployee Inherits class CommissionEmployee Is a CommissionEmployee Has instance variable baseSalaryValue Inherits Public and Protected members Constructor not inherited

37 Outline Commmission Employee.vb (1 of 4 )

38 Outline Commmission Employee.vb (2 of 4 )

39 Outline Commmission Employee.vb (3 of 4 )

40 Outline Commmission Employee.vb (4 of 4 ) Derived classes can now override the CalculateEarnings method

41 Outline Class BasePluCommissionEmployee is a derived class of CommissionEmployee BasePlus Commission Employee.vb (1 of 3 ) Invoke the base class constructor using the base class constructor call syntax

42 Outline BasePlus Commission Employee.vb (2 of 3 ) Compiler generates errors because base class’s instance variable are Private

43 Outline BasePlus Commission Employee.vb (3 of 3 )

44 CommissionEmployee-BasePlusCommissionEmployee Inheritance Hierarchy Using Protected Instance Variables Use protected instance variables Enable class BasePlusCommissionEmployee to directly access base class instance variables Base class’s Protected members are inherited by all derived classes of that base class

45 Outline Declare Protected instance variables (1 of 4 )
Commmission Employee.vb (1 of 4 )

46 Outline Commmission Employee.vb (2 of 4 )

47 Outline Commmission Employee.vb (3 of 4 )

48 Outline Commmission Employee.vb (4 of 4 )

49 Outline (1 of 2 ) Must call base class’s constructor
BasePlus Commission Employee.vb (1 of 2 ) Must call base class’s constructor

50 Outline (2 of 2 ) Overrides base class’s CalculateEarnings method
BasePlus Commission Employee.vb (2 of 2 ) Overrides base class’s CalculateEarnings method Directly access base class’s Protected instance variables

51 Outline Instantiate BasePlusCommissionEmployee object (1 of 2 )
BasePlus Commission EmployeeTest.vb (1 of 2 ) Use BasePluCommissionEmployee’s properties to retrieve and change the object’s instance variable values Explicitly call the object’s overridden ToString method

52 Outline BasePlus Commission EmployeeTest.vb (2 of 2 )

53 CommissionEmployee-BasePlusCommissionEmployee Inheritance Hierarchy Using Protected Instance Variables (Cont.) Using Protected instance variables Advantages Derived classes can modify values directly Slight increase in performance Avoid Set/Get accessors call overhead Disadvantages No validity checking Derived class can assign illegal value Implementation dependent Derived class methods more likely dependent on base class implementation Derived class implementation changes may result in derived class modifications Fragile (brittle) software

54 Software Engineering Observation 10.5
Use the Protected access modifier on a method when a base class is to provide the method to its derived classes but not to other clients.

55 CommissionEmployee-BasePlusCommissionEmployee Inheritance Hierarchy Using Private Instance Variables Reexamine hierarchy Use the best software engineering practice Declare instance variables as Private Provide Public Get and Set accessors Use Get accessor to obtain values of instance variables

56 Software Engineering Observation 10.6
Declaring base class instance variables Private (as opposed to Protected) enables the base class implementation of these instance variables to change without affecting derived class implementations.

57 Error-Prevention Tip 10.1 When possible, do not include Protected instance variables in a base class. Instead, include non-Private properties and methods that carefully access Private instance variables. This will ensure that objects of the derived classes of this base class maintain consistent states of the base class instance variables.

58 Outline Declare Private instance variables (1 of 4 )
Commmission Employee.vb (1 of 4 )

59 Outline Commmission Employee.vb (2 of 4 )

60 Outline Commmission Employee.vb (3 of 4 )

61 Outline Commmission Employee.vb (4 of 4 ) Use properties to obtain the values of instance variables

62 Outline Inherits from CommissionEmployee (1 of 2 )
BasePlus Commission Employee.vb (1 of 2 )

63 Outline BasePlus Commission Employee.vb (2 of 2 ) Invoke an overridden base class method from a derived class Use properties to obtain the values of instance variables Invoke an overridden base class method from a derived class

64 Common Programming Error 10.3
When a base class method is overridden in a derived class, the derived class version often calls the base class version to do a portion of the work. Failure to prefix the base class method name with the keyword MyBase and a dot (.) separator when referencing the base class’s method causes the derived class method to call itself, creating an error called infinite recursion.

65 Outline Create BasePlusCommissionEmployee object. (1 of 2 )
BasePlus Commission EmployeeTest.vb (1 of 2 ) Use inherited properties to access inherited Private instance variables

66 Outline BasePlus Commission EmployeeTest.vb (2 of 2 )

67 10.5 Constructors in Derived Classes
Instantiating derived class object Chain of constructor calls Derived class constructor invokes base class constructor Implicitly or explicitly Base of inheritance hierarchy Last constructor called in chain is Object’s constructor Original derived class constructor’s body finishes executing last Example: CommissionEmployee-BasePlusCommissionEmployee hierarchy CommissionEmployee constructor called second last (last is Object constructor) CommissionEmployee constructor’s body finishes execution second (first is Object constructor’s body) My Class keyword Similar to Me Always invoke the version of the method defined in that particular class Cannot be used to reference Shared class methods They can exist when there are no objects of that class

68 Outline Commission Employee.vb (1 of 4 ) Constructor outputs message to demonstrate method call order.

69 Outline Commission Employee.vb (2 of 4 )

70 Outline Commission Employee.vb (3 of 4 )

71 Outline Commission Employee.vb (4 of 4 )

72 Outline BasePlus Commission Employee.vb (1 of 2 ) Constructor outputs message to demonstrate method call order.

73 Outline BasePlus Commission Employee.vb (2 of 2 )

74 Outline Instantiate CommissionEmployee object
Constructor.vb Instantiate BasePlusCommissionEmployee object to demonstrate order of derived class and base class constructor method calls. Uses the Me reference

75 Outline Uses the MyClass reference

76 10.6 Software Engineering with Inheritance
Customizing existing software Inherit from existing classes Include additional members Redefine base class members No direct access to base class’s source code Link to object code Independent software vendors (ISVs) Develop proprietary code for sale/license Available in object-code format Users derive new classes Without accessing ISV proprietary source code

77 Software Engineering Observation 10.7
Despite the fact that inheriting from a class does not require access to the class’s source code, developers often insist on seeing the source code to see how the class is implemented. They want to ensure that they are extending a solid class that performs well and is implemented securely.

78 Software Engineering Observation 10.8
At the design stage in an object-oriented system, the designer often finds that certain classes are closely related. The designer should “factor out” common instance variables and methods and place them in a base class. Then the designer should use inheritance to develop derived classes, specializing them with capabilities beyond those inherited from the base class.

79 Performance Tip 10.1 If derived classes are larger than they need to be (i.e., contain too much functionality), memory and processing resources may be wasted. Extend the base class that contains the functionality that is closest to what you need.

80 10.7 Class Object Class Object methods Equals Finalize GetHashCode
GetType MemberwiseClone ReferenceEquals ToString

81 Fig. 10. 20 | Object methods that are inherited by all classes
Fig | Object methods that are inherited by all classes. (Part 1 of 3.)

82 Fig. 10. 20 | Object methods that are inherited by all classes
Fig | Object methods that are inherited by all classes. (Part 2 of 3.)

83 Fig. 10. 20 | Object methods that are inherited by all classes
Fig | Object methods that are inherited by all classes. (Part 3 of 3.)

84 10.8 Friend Members Friend Access Another intermediate level
Can be accessed only by code in the same assembly No “special” effect where there is only one class declaration To access a non-Shared Friend member: nameOfObject.nonSharedFriendMember To access a Shared Friend member: nameOfClass. SharedFriendMember Protected Friend Members Are accessible both from code in the same assembly and by derived classes


Download ppt "Object-Oriented Programming: Inheritance"

Similar presentations


Ads by Google