Lecture 5 OOP-Inheritance

download Lecture 5 OOP-Inheritance

of 57

Transcript of Lecture 5 OOP-Inheritance

  • 7/31/2019 Lecture 5 OOP-Inheritance

    1/57

    Click to edit Master subtitle style

    5/25/12

    Inheritance

  • 7/31/2019 Lecture 5 OOP-Inheritance

    2/57

    5/25/12

    Inheritance: Introduction

    Inheritance, is a form of softwarereuse in which a new class is createdby absorbing an existing class's

    members and embellishing themwith new or modified capabilities.

    With inheritance, programmers save

    time during program development byreusing proven and debugged high-quality software. This also increases

    the likelihood that a system will be

  • 7/31/2019 Lecture 5 OOP-Inheritance

    3/57

    5/25/12

    u c ass, recsuperclass and indirect

    superclass A subclass normally adds its own fields and

    methods.

    is more specific than its superclass andrepresents a more specialized group ofobjects.

    In short, it exhibits the behaviors of itssuperclass and other behaviors specificto the subclass.

    The direct superclass is the

  • 7/31/2019 Lecture 5 OOP-Inheritance

    4/57

    5/25/12

    Single and multipleinheritance

    In single inheritance a class isderived from one direct superclass

    Analogy: Cell division (asexualreproduction) one parent

    Java supports only single inheritance

    In multiple inheritance a class isderived from more than one directsuperclass.

    Analogy: sexual reproduction twoparents (or multiple parents for

  • 7/31/2019 Lecture 5 OOP-Inheritance

    5/57

    5/25/12

    Experience in buildingsoftware systems indicates

    that significant amounts ofcode deal with closely-relatedspecial cases. When

    programmers are pre-occupied with special cases,the details can obscure the

    big picture.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    6/57

    5/25/12

    "is-a" versus "has-a"relationship

    We distinguish between the "is-a"relationship and the "has-a"relationship.

    "Is-a" represents inheritance whereby,an object of a subclass can also betreated as an object of its superclass.

    For example, a car is a vehicle. "has-a" represents composition

    whereby, an object contains one ormore object references as members. For

    example, a car has a steering wheel

  • 7/31/2019 Lecture 5 OOP-Inheritance

    7/57

    5/25/12

    Inheritance Examples: inGeometry

    Often, an object of one class "is an"object of another class as well. Forexample, in geometry,

    a rectangle is a quadrilateral

    class Rectangle can be said to inherit fromclass Quadrilateral.

    class Quadrilateral is a superclass and

    class Rectangle is a subclass.

    A rectangle is a specific type of

    quadrilateral, but it is incorrect to claim thatevery quadrilateral is a rectangle. the

  • 7/31/2019 Lecture 5 OOP-Inheritance

    8/57

    5/25/12

    Inheritance: OtherExamples

    Superclass Subclasses

    Student PhDStudent, GraduateStudent,UndergraduateStudent

    Shape Circle, Triangle, Rectangle

    Loan CarLoan, HomeImprovementLoan,

    MortgageLoan

    Employee Faculty, Staff

    BankAccount CheckingAccount, SavingsAccount

  • 7/31/2019 Lecture 5 OOP-Inheritance

    9/57

    5/25/12

    Because every subclass object "isan" object of its superclass, and onesuperclass can have many

    subclasses, the set of objectsrepresented by a superclass istypically larger than the set of

    objects represented by any of itssubclasses.

    For example, the superclass Vehiclerepresents all vehicles, including cars,trucks, boats, bicycles and so on.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    10/57

    5/25/12

    Inheritance hierarchy: universityCommunityMembers

    A university community hasthousands of members, includingemployees, students and alumni.

    Employees are either faculty membersor staff members.

    Faculty members are either

    administrators (such as deans anddepartment chairpersons) or teachers.Note that the hierarchy could containmany other classes. For example,

    students can be graduate or

  • 7/31/2019 Lecture 5 OOP-Inheritance

    11/57

    5/25/12

    Each arrow in the hierarchyrepresents an "is-a" relationship. Aswe follow the arrows in this class

    hierarchy, we can state, for instance,that

    "an Employee is a CommunityMember"

    and "a Teacher is a Faculty member."

    CommunityMember is the direct

    superclass of Employee, Student and

  • 7/31/2019 Lecture 5 OOP-Inheritance

    12/57

    5/25/12

    Inheritance hierarchy:for Shapes

  • 7/31/2019 Lecture 5 OOP-Inheritance

    13/57

    5/25/12

    Has a Relationship

    In "has-a" relationship, classes havemembers that are references toobjects of other classes. Such

    relationships create classes bycomposition of existing classes. Forexample, given the classes

    Employee, BirthDate andTelephoneNumber,

    it is improper to say that an Employee isa BirthDate or that an Employee is a

    TelephoneNumber.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    14/57

    5/25/12

    Problems of Inheritance

    A subclass can inherit methods thatit does not need or should not have.

    Even when a superclass method isappropriate for a subclass, thatsubclass often needs a customizedversion of the method. In such cases,

    the subclass can override(redefine) the superclass methodwith an appropriate implementation.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    15/57

    5/25/12

    Public versus privatemembers

    A class's public members areaccessible wherever the program hasa reference to an object of that class

    or one of its subclasses. A class's private members are

    accessible only from within the class

    itself. A superclass's private members are not

    inherited by its subclasses.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    16/57

    5/25/12

    protected Members

    Using protected access offers anintermediate level of access betweenpublic and private.

    A superclass's protected members can beaccessed by members of thatsuperclass, by members of its

    subclasses and by members ofotherclasses in the same package (i.e.,protected members also have packageaccess).

    All public and protected superclass

  • 7/31/2019 Lecture 5 OOP-Inheritance

    17/57

    5/25/12

    Software Engineering Observation

    Methods of a subclass cannot directlyaccess private members of their

    superclass. A subclass can change thestate of private superclass instancevariables only through non-private(public, protected) methods providedin the superclass and inherited by thesubclass.

    Declaring private instance variables

    helps programmers test, debug and

  • 7/31/2019 Lecture 5 OOP-Inheritance

    18/57

    5/25/12

    e a ons p e weenSuperclasses and

    Subclasses Consider types of employees in acompany's payroll application todiscuss the relationship between a

    superclass and its subclass. commission employees (who will be

    represented as objects of a superclass)

    are paid a percentage of their sales base-salaried commission

    employees (who will be represented asobjects of a subclass) receive a basesalary plus a percentage of their sales.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    19/57

    5/25/12

    ClassCommissionEmployee

    1st example: class CommissionEmployee directly inherits fromclass Object and declares as private instance variables a first name,last name, social security number, commission rate and gross (i.e.,total) sales amount.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    20/57

    5/25/12

    Creating aBasePlusCommissionEmployee Class

    without Using Inheritance 2nd example: class BasePlusCommissionEmployee directly

    inherits from class Object and declares as private instance variablesa first name, last name, social security number, commission rate,gross sales amount and base salary.

    This class BasePlusCommissionEmployee is created by writing every line of

    code the class requires.

    it is more efficient to create this class by inheriting from classCommissionEmployee.

    This example declares and tests (a completely new andindependent) class BasePlusCommissionEmployee, which contains a

    first name, last name, social security number, gross sales amount,commission rate and base salary. ClassBasePlusCommissionEmployee's public services include aBasePlusCommissionEmployee constructor and methods earningsand toString. declare public get and set methods for the class'sprivate instance variables firstName, lastName,

    socialSecurityNumber, grossSales, commissionRate and baseSalary.These variables and methods encapsulate all the necessary

  • 7/31/2019 Lecture 5 OOP-Inheritance

    21/57

    5/25/12

  • 7/31/2019 Lecture 5 OOP-Inheritance

    22/57

    5/25/12

    Software Engineering Observation

    Copying and pasting code from oneclass to another can spread errors

    across multiple source code files. Toavoid duplicating code (and possiblyerrors), use inheritance, rather than the"copy-and-paste" approach, in situations

    where you want one class to "absorb"the instance variables and methods ofanother class.

    With inheritance, the common instance

  • 7/31/2019 Lecture 5 OOP-Inheritance

    23/57

    5/25/12

    Creating a CommissionEmployeeBasePlusCommissionEmployee

    Inheritance Hierarchy

    3rd example: declares a separateBasePlusCommissionEmployee2class that extends class

    CommissionEmployee (i.e., aBasePlusCommissionEmployee2 is aCommissionEmployee who also has abase salary) and attempts to access

    class CommissionEmployee's privatemembers. This results in compilationerrors, because the subclass cannotaccess the superclass's private instance

    variables.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    24/57

    5/25/12

    Each subclass constructor mustimplicitly or explicitly call its

    superclass constructor to ensure thatthe instance variables inherited fromthe superclass are initialized properly.

    BasePlusCommissionEmployee2's six-argument constructor explicitly callsclass CommissionEmployee's five-argument constructor to initialize the

    superclass portion of aBasePlusCommissionEmployee2 object.

    BasePlusCommissionEmployee2's six-argument constructor invokes theCommissionEmployee's five-argument

  • 7/31/2019 Lecture 5 OOP-Inheritance

    25/57

    5/25/12

  • 7/31/2019 Lecture 5 OOP-Inheritance

    26/57

    5/25/12

  • 7/31/2019 Lecture 5 OOP-Inheritance

    27/57

    5/25/12

    CommissionEmployeeBasePlusCommissionEmployee Inheritance HierarchyUsing protected Instance Variables

    4th example: we show that ifCommissionEmployee's instancevariables are declared as protected,

    aBasePlusCommissionEmployee3class that extends class

    CommissionEmployee2 can accessthat data directly.

    declare class CommissionEmployee2with protected instance variables.

    omm ss on mp oyee ase us o

  • 7/31/2019 Lecture 5 OOP-Inheritance

    28/57

    5/25/12

    omm ss on mp oyee ase us ommissionEmployee Inheritance

    Hierarchy Using protected

    Instance Variables A superclass's protected members areinherited by all subclasses of thatsuperclass.

    Class CommissionEmployee2 is amodification of classCommissionEmployee that declaresinstance variables firstName, lastName,

    socialSecurityNumber, grossSales andcommissionRate as protected ratherthan private.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    29/57

    5/25/12

    ClassBasePlusCommissionEmployee3 doesnot inherit class

    CommissionEmployee2's constructor. However, class

    BasePlusCommissionEmployee3's

    six-argument constructor calls classCommissionEmployee2's five-argument constructor explicitly.

    BasePlusCommissionEmployee3's six-

  • 7/31/2019 Lecture 5 OOP-Inheritance

    30/57

    5/25/12

  • 7/31/2019 Lecture 5 OOP-Inheritance

    31/57

    5/25/12

  • 7/31/2019 Lecture 5 OOP-Inheritance

    32/57

    5/25/12

    STOP HERE

  • 7/31/2019 Lecture 5 OOP-Inheritance

    33/57

    5/25/12

    In this example, we declaredsuperclass instance variables asprotected so that subclasses could

    inherit them. Inheriting protected instance

    variables slightly increases

    performance, because we candirectly access the variables in thesubclass without incurring the

    overhead of a set or get method call.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    34/57

    5/25/12

    Software Engineering Observation

    The Java compiler sets the superclass ofa class to Object when the class

    declaration does not explicitly extend asuperclass.

    Common Programming Error

    It is a syntax error to override a methodwith a more restricted access modifier.

    A public method of the superclass

    cannot become a protected or private

  • 7/31/2019 Lecture 5 OOP-Inheritance

    35/57

    5/25/12

    Programming Tips

    Constructors are not inherited,

    so class CommissionEmployee does notinherit class Object's constructor.

    However, class CommissionEmployee'sconstructor calls class Object'sconstructor implicitly.

    the first task of any subclass constructoris to call its direct superclass'sconstructor, either explicitly or implicitly(if no constructor call is specified), to

    ensure that the instance variables

  • 7/31/2019 Lecture 5 OOP-Inheritance

    36/57

    5/25/12

    Problems with protected instancevariables

    Using protected instance variablescreates several potential problems.

    First, the subclass object can set an

    inherited variable's value directlywithout using a set method. Therefore, asubclass object can assign an invalidvalue to the variable, thus leaving theobject in an inconsistent state. Forexample, if we were to declareCommissionEmployee3's instancevariable grossSales as protected, asubclass ob ect e. .,

  • 7/31/2019 Lecture 5 OOP-Inheritance

    37/57

    5/25/12

    Software Engineering Observation

    Use the protected access modifier whena superclass should provide a method

    only to its subclasses and other classesin the same package, but not to otherclients.

    Software Engineering Observation Declaring superclass instance variables

    private (as opposed to protected)enables the superclass implementationof these instance variables to change

  • 7/31/2019 Lecture 5 OOP-Inheritance

    38/57

    C i i E l B Pl C i

  • 7/31/2019 Lecture 5 OOP-Inheritance

    39/57

    5/25/12

    CommissionEmployeeBasePlusCommissionEmployee Inheritance Hierarchy

    Using private Instance Variables

    Lets now use the best softwareengineering practices.

    Class CommissionEmployee3 declares

    all instance variables as private andprovides some public methods (seemethod list below) for manipulatingthese values.

    methods earnings and toString usethe class's get methods to obtain thevalues of its instance variables.

    If we decide to change the instance variable

    instance variables: firstName, lastName, socialSecurityNumber,grossSales and commissionRate

    methods: setFirstName, getFirstName, setLastName,

    getLastName, setSocialSecurityNumber, getSocialSecurityNumber,setGrossSales, getGrossSales, setCommissionRate, getCommissionRate,

  • 7/31/2019 Lecture 5 OOP-Inheritance

    40/57

    5/25/12

    ClassBasePlusCommissionEmployee4 hasseveral changes to its method

    implementations that distinguish itfrom classBasePlusCommissionEmployee3.

    Methods earnings and toString eachinvoke method getBaseSalary to obtainthe base salary value, rather thanaccessing baseSalary directly. If we

    decide to rename instance variable

  • 7/31/2019 Lecture 5 OOP-Inheritance

    41/57

    5/25/12

    BasePlusCommissionEmployee4'stoString method overrides classCommissionEmployee3's toStringmethod to return a string representationthat is appropriate for a base-salariedcommission employee. The new versioncreates part of a

    BasePlusCommissionEmployee4 object'sstring representation (i.e., the string"commission employee" and the valuesof class CommissionEmployee3's private

    instance variables) by calling'

  • 7/31/2019 Lecture 5 OOP-Inheritance

    42/57

    5/25/12

    Software Engineering Observation:

    if a method performs all or some of the actionsneeded by another method, call that method ratherthan duplicate its code. By having

    BasePlusCommissionEmployee4's earnings methodinvoke CommissionEmployee3's earnings method tocalculate part of a BasePlusCommissionEmployee4object's earnings, we avoid duplicating the code andreduce code-maintenance problems.

    Common Programming Error

    When a superclass method is overridden in asubclass, the subclass version often calls the

    superclass version to do a portion of the work.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    43/57

    5/25/12

    Conclusion

    In this section, we have shown youan evolutionary set of examples thatwas carefully designed to teach key

    capabilities for good softwareengineering with inheritance.

    You learned

    how to use the keyword extends tocreate a subclass using inheritance

    how to use protected superclass

    members to enable a subclass to access

    C t t i

  • 7/31/2019 Lecture 5 OOP-Inheritance

    44/57

    5/25/12

    Constructors inSubclasses

    Instantiating a subclass object beginsa chain of constructor calls in whichthe subclass constructor, before

    performing its own tasks, invokes itsdirect superclass's constructor eitherexplicitly (via the super reference) or

    implicitly (calling the superclass'sdefault constructor or no-argumentconstructor).

    Similarly, if the superclass is derived

  • 7/31/2019 Lecture 5 OOP-Inheritance

    45/57

    5/25/12

    Software Engineering Observation

    When a program creates a subclassobject, the subclass constructor

    immediately calls the superclassconstructor (explicitly, via super, orimplicitly). The superclass constructor'sbody executes to initialize the

    superclass's instance variables that arepart of the subclass object, then thesubclass constructor's body executes toinitialize the subclass-only instance

    variables. Java ensures that even if a

  • 7/31/2019 Lecture 5 OOP-Inheritance

    46/57

    5/25/12

    Our next example declares a

    CommissionEmployee4 classcontaining the same features as

    CommissionEmployee.

    The constructor is modified to output textupon its invocation.

    BasePlusCommissionEmployee5class is almost identical to

    BasePlusCommissionEmployee4, except'

    O d f C t t

  • 7/31/2019 Lecture 5 OOP-Inheritance

    47/57

    5/25/12

    Orders of ConstructorExecution

    O d f C t t

  • 7/31/2019 Lecture 5 OOP-Inheritance

    48/57

    5/25/12

    Orders of ConstructorExecution

    Class ConstructorTest demonstratesthe order in which constructors arecalled for objects of classes that are

    part of an inheritance hierarchy. Method main begins by instantiating

    CommissionEmployee4 object

    employee1. instantiate

    BasePlusCommissionEmployee5 objectemployee2. This invokes the

    CommissionEmployee4 constructor,

    S ft E i i

  • 7/31/2019 Lecture 5 OOP-Inheritance

    49/57

    5/25/12

    Software Engineeringwith Inheritance

    When a new class extends anexisting class, the new class inheritsthe non-private members of the

    existing class. We can customize the new class to

    meet our needs by

    including additional members and by

    overriding superclass members. Doingthis does not require the subclass

    programmer to change the superclass's

  • 7/31/2019 Lecture 5 OOP-Inheritance

    50/57

    5/25/12

    Sometimes, students have difficultyappreciating the scope of theproblems faced by designers who

    work on large-scale software projectsin industry. People experienced withsuch projects say that effective

    software reuse improves the softwaredevelopment process. Object-oriented programming facilitatessoftware reuse, potentially

    shortening development time.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    51/57

    5/25/12

    Object Class

    All classes in Java inherit directly orindirectly from the Object class(package java.lang), so its 11

    methods are inherited by all otherclasses. Figure 9.18 summarizesObject's methods.

    ec me o s a are

  • 7/31/2019 Lecture 5 OOP-Inheritance

    52/57

    5/25/12

    ec me o s a areinherited directly or

    indirectly by all classes clone This protected method, which takes no

    arguments and returns an Object

    reference, makes a copy of the object onwhich it is called. When cloning isrequired for objects of a class, the classshould override method clone as a

    public method and should implementinterface Cloneable (package java.lang).

    The default implementation of thismethod performs a so-called shallow

    copyinstance variable values in one

  • 7/31/2019 Lecture 5 OOP-Inheritance

    53/57

    5/25/12

    Equals

    This method compares two objects forequality and returns TRue if they are

    equal and false otherwise. The methodtakes any Object as an argument. Whenobjects of a particular class must becompared for equality, the class should

    override method equals to compare thecontents of the two objects.

    The method's implementation shouldmeet the following requirements:

  • 7/31/2019 Lecture 5 OOP-Inheritance

    54/57

    5/25/12

    finalize

    This protected method is called by thegarbage collector to perform termination

    housekeeping on an object just beforethe garbage collector reclaims theobject's memory. It is not guaranteedthat the garbage collector will reclaim

    an object, so it cannot be guaranteedthat the object's finalize method willexecute. The method must specify anempty parameter list and must return

    void. The default implementation of this

  • 7/31/2019 Lecture 5 OOP-Inheritance

    55/57

    5/25/12

    hashCode

    A hashtable is a data structure(discussed in Section 19.10) that relates

    one object, called the key, to anotherobject, called the value. When initiallyinserting a value into a hashtable, thekey's hashCode method is called. The

    hashcode value returned is used by thehashtable to determine the location atwhich to insert the corresponding value.

    The key's hashcode is also used by the

    hashtable to locate the key's

  • 7/31/2019 Lecture 5 OOP-Inheritance

    56/57

    5/25/12

    toString

    This method returns a Stringrepresentation of an object. The default

    implementation of this method returnsthe package name and class name ofthe object's class followed by ahexadecimal representation of the value

    returned by the object's hashCodemethod.

  • 7/31/2019 Lecture 5 OOP-Inheritance

    57/57

    Software Engineering Observation9.10

    At the design stage in an object-oriented

    system, the designer often finds thatcertain classes are closely related. Thedesigner should "factor out" commoninstance variables and methods and

    place them in a superclass. Then thedesigner should use inheritance todevelop subclasses, specializing themwith capabilities beyond those inherited