Kĩ thuật lập trình - Object - Oriented programming: Inheritance
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 superclass. Then the designer should use inheritance to develop subclasses, specializing them with capabilities beyond those inherited from the superclass.
89 trang |
Chia sẻ: huyhoang44 | Lượt xem: 911 | Lượt tải: 0
Bạn đang xem trước 20 trang tài liệu Kĩ thuật lập trình - Object - Oriented programming: Inheritance, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
9Object-Oriented Programming: Inheritance1 Say not you know another entirely, till you have divided an inheritance with him.Johann Kasper LavaterThis method is to define as the number of a class the class of all classes similar to the given class.Bertrand RussellGood as it is to inherit a library, it is better to collect one. Augustine BirrellSave base authority from others' books.William Shakespeare2OBJECTIVESIn this chapter you will learn: How inheritance promotes software reusability.The notions of superclasses and subclasses.To use keyword extends to create a class that inherits attributes and behaviors from another class.To use access modifier protected to give subclass methods access to superclass members.To access superclass members with super.How constructors are used in inheritance hierarchies.The methods of class Object, the direct or indirect superclass of all classes in Java.39.1 Introduction 9.2 Superclasses and Subclasses 9.3 protected Members 9.4 Relationship between Superclasses and Subclasses 9.4.1 Creating and Using a CommissionEmployee Class 9.4.2 Creating a BasePlusCommissionEmployee Class without Using Inheritance 9.4.3 Creating a CommissionEmployee– BasePlusCommissionEmployee Inheritance Hierarchy 9.4.4 CommissionEmployee– BasePlusCommissionEmployee Inheritance Hierarchy Using protected Instance Variables 9.4.5 CommissionEmployee– BasePlusCommissionEmployee Inheritance Hierarchy Using private Instance Variables 49.5 Constructors in Subclasses 9.6 Software Engineering with Inheritance 9.7 Object Class 9.8 (Optional) GUI and Graphics Case Study: Displaying Text and Images Using Labels9.9 Wrap-Up 59.1 IntroductionInheritanceSoftware reusabilityCreate new class from existing classAbsorb existing class’s data and behaviorsEnhance with new capabilitiesSubclass extends superclassSubclassMore specialized group of objectsBehaviors inherited from superclassCan customizeAdditional behaviors69.1 Introduction (Cont.)Class hierarchyDirect superclassInherited explicitly (one level up hierarchy)Indirect superclassInherited two or more levels up hierarchySingle inheritanceInherits from one superclassMultiple inheritanceInherits from multiple superclassesJava does not support multiple inheritance79.2 Superclasses and subclassesSuperclasses and subclassesObject of one class “is an” object of another classExample: Rectangle is quadrilateral.Class Rectangle inherits from class QuadrilateralQuadrilateral: superclassRectangle: subclassSuperclass typically represents larger set of objects than subclassesExample: superclass: VehicleCars, trucks, boats, bicycles, subclass: CarSmaller, more-specific subset of vehicles8Fig. 9.1 | Inheritance examples. 99.2 Superclasses and subclasses (Cont.)Inheritance hierarchyInheritance relationships: tree-like hierarchy structureEach class becomessuperclassSupply members to other classesORsubclassInherit members from other classes10Fig. 9.2 | Inheritance hierarchy for university CommunityMembers 11Fig. 9.3 | Inheritance hierarchy for Shapes. 129.3 protected Membersprotected accessIntermediate level of protection between public and privateprotected members accessible bysuperclass memberssubclass membersClass members in the same packageSubclass access to superclass memberKeyword super and a dot (.)13Software Engineering Observation 9.1Methods of a subclass cannot directly access private members of their superclass. A subclass can change the state of private superclass instance variables only through non-private methods provided in the superclass and inherited by the subclass. 14Software Engineering Observation 9.2Declaring private instance variables helps programmers test, debug and correctly modify systems. If a subclass could access its superclass’s private instance variables, classes that inherit from that subclass 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. 159.4 Relationship between Superclasses and SubclassesSuperclass and subclass relationshipExample: CommissionEmployee/BasePlusCommissionEmployee inheritance hierarchyCommissionEmployeeFirst name, last name, SSN, commission rate, gross sale amountBasePlusCommissionEmployeeFirst name, last name, SSN, commission rate, gross sale amountBase salary169.4.1 Creating and Using a CommissionEmployee ClassClass CommissionEmployeeExtends class ObjectKeyword extendsEvery class in Java extends an existing classExcept ObjectEvery class inherits Object’s methodsNew class implicitly extends ObjectIf it does not extend another class17Software Engineering Observation 9.3The Java compiler sets the superclass of a class to Object when the class declaration does not explicitly extend a superclass. 18OutlineCommissionEmployee.java(1 of 4)Line 4Lines 6-10Line 16Lines 17-21Lines 20-21Class CommissionEmployee extends class ObjectImplicit call to Object constructorInitialize instance variablesDeclare private instance variablesInvoke methods setGrossSales and setCommissionRate to validate data19OutlineCommissionEmployee.java(2 of 4)20OutlineCommissionEmployee.java(3 of 4)Lines 85-88Calculate earnings21OutlineCommissionEmployee.java(4 of 4)Lines 91-98Override method toString of class Object22Common Programming Error 9.1It is a syntax error to override a method with a more restricted access modifier—a public method of the superclass cannot become a protected or private method in the subclass; a protected method of the superclass cannot become a private method in the subclass. Doing so would break the “is-a” relationship in which it is required that all subclass objects be able to respond to method calls that are made to public methods declared in the superclass.(cont)23Common Programming Error 9.1If a public method could be overridden as a protected or private method, the subclass objects would not be able to respond to the same method calls as superclass objects. Once a method is declared public in a superclass, the method remains public for all that class’s direct and indirect subclasses. 24OutlineCommissionEmployeeTest.java(1 of 2)Lines 9-10Lines 15-25Line 26-27Instantiate CommissionEmployee objectUse CommissionEmployee’s get methods to retrieve the object’s instance variable valuesUse CommissionEmployee’s set methods to change the object’s instance variable values25OutlineCommissionEmployeeTest.java(2 of 2)Line 30Program outputImplicitly call object’s toString method269.4.2 Creating a BasePlusCommissionEmployee Class without Using InheritanceClass BasePlusCommissionEmployeeImplicitly extends ObjectMuch of the code is similar to CommissionEmployeeprivate instance variablespublic methodsconstructorAdditionsprivate instance variable baseSalaryMethods setBaseSalary and getBaseSalary27OutlineBasePlusCommissionEmployee.java(1 of 4)Line 12Line 24Add instance variable baseSalaryUse method setBaseSalary to validate data28OutlineBasePlusCommissionEmployee.java(2 of 4)29OutlineBasePlusCommissionEmployee.java(3 of 4)30OutlineBasePlusCommissionEmployee.java(4 of 4)Lines 88-91Lines 94-97Line 102Lines 108-113Method setBaseSalary validates data and sets instance variable baseSalaryMethod getBaseSalary returns the value of instance variable baseSalaryUpdate method earnings to calculate the earnings of a base-salaried commission employeeUpdate method toString to display base salary 31OutlineBasePlusCommissionEmployeeTest.java(1 of 2)Line 9-11Lines 16-27Instantiate BasePlusCommissionEmployee objectUse BasePluCommissionEmployee’s get methods to retrieve the object’s instance variable values32OutlineBasePlusCommissionEmployeeTest.java(2 of 2)Line 29Line 33Program outputUse BasePlusCommissionEmployee’s setBaseSalary methods to set base salaryExplicitly call object’s toString method33Software Engineering Observation 9.4Copying and pasting code from one class to another can spread errors across multiple source code files. To avoid duplicating code (and possibly errors), use inheritance, rather than the “copy-and-paste” approach, in situations where you want one class to “absorb” the instance variables and methods of another class. 34Software Engineering Observation 9.5With inheritance, the common instance variables and methods of all the classes in the hierarchy are declared in a superclass. When changes are required for these common features, software developers need only to make the changes in the superclass—subclasses then inherit the changes. Without inheritance, changes would need to be made to all the source code files that contain a copy of the code in question. 359.4.3 Creating a CommissionEmployee-BasePlusCommiionEmployee Inheritance HierarchyClass BasePlusCommissionEmployee2Extends class CommissionEmployeeIs a CommissionEmployeeHas instance variable baseSalaryInherits public and protected membersConstructor not inherited36OutlineBasePlusCommissionEmployee2.java(1 of 3)Line 4Line 13Class BasePluCommissionEmployee2 is a subclass of CommissionEmployeeInvoke the superclass constructor using the superclass constructor call syntax37OutlineBasePlusCommissionEmployee2.java(2 of 3)Line 34Lines 41-46Compiler generates errors because superclass’s instance variable commissionRate and grossSales are privateCompiler generates errors because superclass’s instance variable firstName, lastName, socialSecurityNumber, grossSales and commissionRate are private38OutlineBasePlusCommissionEmployee2.java(3 of 3)Compiler generated errorss39Common Programming Error 9.2A compilation error occurs if a subclass constructor calls one of its superclass constructors with arguments that do not match exactly the number and types of parameters specified in one of the superclass constructor declarations. 409.4.4 CommissionEmployee-BasePlusCommissionEmployee Inheritance Hierarchy Using protected Instance VariablesUse protected instance variablesEnable class BasePlusCommissionEmployee to directly access superclass instance variablesSuperclass’s protected members are inherited by all subclases of that superclass41OutlineCommissionEmployee2.java(1 of 4)Line 6-10Declare protected instance variables42OutlineCommissionEmployee2.java(2 of 4)43OutlineCommissionEmployee2.java(3 of 4)44OutlineCommissionEmployee2.java(4 of 4)45OutlineBasePlusCommissionEmployee3.java(1 of 2)Line 13Must call superclass’s constructor46OutlineBasePlusCommissionEmployee3.java(2 of 2)Line 32Lines 38-43Directly access superclass’s protected instance variables47OutlineBasePlusCommissionEmployeeTest3.java(1 of 2)48OutlineBasePlusCommissionEmployeeTest3.java(2 of 2)Program output499.4.4 CommissionEmployee-BasePlusCommissionEmployee Inheritance Hierarchy Using protected Instance Variables (Cont.)Using protected instance variablesAdvantagessubclasses can modify values directlySlight increase in performanceAvoid set/get method call overheadDisadvantagesNo validity checkingsubclass can assign illegal valueImplementation dependentsubclass methods more likely dependent on superclass implementationsuperclass implementation changes may result in subclass modificationsFragile (brittle) software50Software Engineering Observation 9.6Use the protected access modifier when a superclass should provide a method only to its subclasses and other classes in the same package, but not to other clients. 51Software Engineering Observation 9.7 Declaring superclass instance variables private (as opposed to protected) enables the superclass implementation of these instance variables to change without affecting subclass implementations. 52Error-Prevention Tip 9.1 When possible, do not include protected instance variables in a superclass. Instead, include non-private methods that access private instance variables. This will ensure that objects of the class maintain consistent states. 539.4.5 CommissionEmployee-BasePlusCommissionEmployee Inheritance Hierarchy Uing private Instance VariablesReexamine hierarchyUse the best software engineering practiceDeclare instance variables as privateProvide public get and set methodsUse get method to obtain values of instance variables54OutlineCommissionEmployee3.java(1 of 4)Lines 6-10Declare private instance variables55OutlineCommissionEmployee3.java(2 of 4)56OutlineCommissionEmployee3.java(3 of 4)57OutlineCommissionEmployee3.java(4 of 4)Line 87Lines 94-97Use get methods to obtain the values of instance variables58OutlineBasePlusCommissionEmployee4.java(1 of 2)Inherits from CommissionEmployee359OutlineBasePlusCommissionEmployee4.java(2 of 2)Line 33 & 40Line 33Lines 40Use get methods to obtain the values of instance variablesInvoke an overridden superclass method from a subclassInvoke an overridden superclass method from a subclass60Common Programming Error 9.3 When a superclass method is overridden in a subclass, the subclass version often calls the superclass version to do a portion of the work. Failure to prefix the superclass method name with the keyword super and a dot (.) separator when referencing the superclass’s method causes the subclass method to call itself, creating an error called infinite recursion. Recursion, used correctly, is a powerful capability discussed in Chapter 15, Recursion. 61OutlineBasePlusCommissionEmployeeTest4.java(1 of 2)Lines 9-11Lines 16-25Create BasePlusCommissionEmployee4 object.Use inherited get methods to access inherited private instance variablesUse BasePlusCommissionEmployee4 get method to access private instance variable.62OutlineBasePlusCommissionEmployeeTest4.java(2 of 2)Use BasePlusCommissionEmployee4 set method to modify private instance variable baseSalary.639.5 Constructors in SubclassesInstantiating subclass objectChain of constructor callssubclass constructor invokes superclass constructorImplicitly or explicitlyBase of inheritance hierarchyLast constructor called in chain is Object’s constructorOriginal subclass constructor’s body finishes executing lastExample: CommissionEmployee3-BasePlusCommissionEmployee4 hierarchyCommissionEmployee3 constructor called second last (last is Object constructor)CommissionEmployee3 constructor’s body finishes execution second (first is Object constructor’s body)64Software Engineering Observation 9.8 When a program creates a subclass object, the subclass constructor immediately calls the superclass constructor (explicitly, via super, or implicitly). The superclass constructor’s body executes to initialize the superclass’s instance variables that are part of the subclass object, then the subclass constructor’s body executes to initialize the subclass-only instance variables.(cont)65Software Engineering Observation 9.8 Java ensures that even if a constructor does not assign a value to an instance variable, the variable is still initialized to its default value (e.g., 0 for primitive numeric types, false for booleans, null for references). 66OutlineCommissionEmployee4.java(1 of 4)Lines 23-24Constructor outputs message to demonstrate method call order.67OutlineCommissionEmployee4.java(2 of 4)68OutlineCommissionEmployee4.java(3 of 4)69OutlineCommissionEmployee4.java(4 of 4)70OutlineBasePlusCommissionEmployee5.java(1 of 2)Lines 15-16Constructor outputs message to demonstrate method call order.71OutlineBasePlusCommissionEmployee5.java(2 of 2)72OutlineConstructorTest.java(1 of 2)Lines 8-9Lines 12-19Instantiate two BasePlusCommissionEmployee5 objects to demonstrate order of subclass and superclass constructor method calls.Instantiate CommissionEmployee4 object73OutlineConstructorTest.java(2 of 2)Subclass BasePlusCommissionEmployee5 constructor body executes after superclass CommissionEmployee4’s constructor finishes execution.749.6 Software Engineering with InheritanceCustomizing existing softwareInherit from existing classesInclude additional membersRedefine superclass membersNo direct access to superclass’s source codeLink to object codeIndependent software vendors (ISVs)Develop proprietary code for sale/licenseAvailable in object-code formatUsers derive new classes Without accessing ISV proprietary source code75Software Engineering Observation 9.9Despite 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 understand how the class is implemented. Developers in industry want to ensure that they are extending a solid class—for example, a class that performs well and is implemented securely. 76Software Engineering Observation 9.10At 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 superclass. Then the designer should use inheritance to develop subclasses, specializing them with capabilities beyond those inherited from the superclass. 77Software Engineering Observation 9.11Declaring a subclass does not affect its superclass’s source code. Inheritance preserves the integrity of the superclass. 78Software Engineering Observation 9.12Just as designers of non-object-oriented systems should avoid method proliferation, designers of object-oriented systems should avoid class proliferation. Such proliferation creates management problems and can hinder software reusability, because in a huge class library it becomes difficult for a client to locate the most appropriate classes. The alternative is to create fewer classes that provide more substantial functionality, but such classes might prove cumbersome. 79Performance Tip 9.1If subclasses are larger than they need to be (i.e., contain too much functionality), memory and processing resources might be wasted. Extend the superclass that contains the functionality that is closest to what is needed. 809.7 Object ClassClass Object methodscloneequalsfinalizegetClasshashCodenotify, notifyAll, waittoString81Fig. 9.18 | Object methods that are inherited directly or indirectly by all classes.(Part 1 of 4) 82Fig. 9.18 | Object methods that are inherited directly or indirectly by all classes.(Part 2 of 4) 83Fig. 9.18 | Object methods that are inherited directly or indirectly by all classes. (Part 3 of 4)84Fig. 9.18 | Object methods that are inherited directly or indirectly by all classes. (Part 4 of 4) 859.8 (Optional) GUI and Graphics Case Study: Displaying Text and Images Using LabelsLabelsDisplay information and instructionsJLabelDisplay a single line of textDisplay an imageDisplay both text and image86OutlineLabelDemo.java(1 of 2)Line 13Line 16Line 19Line 25Change the text the southLabel displaysImageIcon constructor argument specifies the path to the imageDeclare and initialize centerLabel with a JLabel that displays the labelIconCreate a JLabel that displays the string “North”87OutlineLabelDemo.java(2 of 2)Lines 34-36Attach the labels to the JFrame at north, center and south88Fig. 9.20 | JLabel displaying shape statistics. 89
Các file đính kèm theo tài liệu này:
- javahtp7e_09_05_0766.ppt