You are on page 1of 57

Inheritance

Click to edit Master subtitle style

5/25/12

Inheritance: Introduction

Inheritance, is a form of software reuse in which a new class is created by absorbing an existing class's members and embellishing them with new or modified capabilities. With inheritance, programmers save time during program development by reusing proven and debugged highquality software. This also increases the likelihood that a system will be 5/25/12

A subclass

Subclass, direct superclass and indirect superclass


normally adds its own fields and methods. is more specific than its superclass and represents a more specialized group of objects. In short, it exhibits the behaviors of its superclass and other behaviors specific to the subclass.

5/25/12

The direct superclass is the

Single and multiple inheritance

In single inheritance a class is derived from one direct superclass

Analogy: Cell division (asexual reproduction) one parent Java supports only single inheritance

In multiple inheritance a class is derived from more than one direct superclass.
Analogy: sexual reproduction two 5/25/12 parents (or multiple parents for

5/25/12

Experience in building software systems indicates that significant amounts of code deal with closely-related special cases. When programmers are preoccupied with special cases, the details can obscure the big picture.

"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 be treated as an object of its superclass. For example, a car is a vehicle.

"has-a" represents composition whereby, an object contains one or more object references as members. For 5/25/12 example, a car has a steering wheel

Inheritance Examples: in Geometry

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

a rectangle is a quadrilateral

class Rectangle can be said to inherit from class 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 that every quadrilateral is a rectangle. the

5/25/12

Inheritance: Other Examples


Superclass Subclasses Student PhDStudent, GraduateStudent, UndergraduateStudent Shape Loan Circle, Triangle, Rectangle CarLoan, HomeImprovementLoan, MortgageLoan Employee
5/25/12 BankAccount

Faculty, Staff CheckingAccount, SavingsAccount

Because every subclass object "is an" object of its superclass, and one superclass can have many subclasses, the set of objects represented by a superclass is typically larger than the set of objects represented by any of its subclasses.
For example, the superclass Vehicle represents all vehicles, including cars, 5/25/12 trucks, boats, bicycles and so on.

Inheritance hierarchy: university CommunityMembers

A university community has thousands of members, including employees, students and alumni.

Employees are either faculty members or staff members.

Faculty members are either administrators (such as deans and department chairpersons) or teachers. Note that the hierarchy could contain many other classes. For example, 5/25/12 students can be graduate or

Each arrow in the hierarchy represents an "is-a" relationship. As we 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 5/25/12

Inheritance hierarchy: for Shapes

5/25/12

Has a Relationship

In "has-a" relationship, classes have members that are references to objects of other classes. Such relationships create classes by composition of existing classes. For example, given the classes Employee, BirthDate and TelephoneNumber,
it is improper to say that an Employee is a BirthDate or that an Employee is a 5/25/12 TelephoneNumber.

Problems of Inheritance

A subclass can inherit methods that it does not need or should not have. Even when a superclass method is appropriate for a subclass, that subclass often needs a customized version of the method. In such cases, the subclass can override (redefine) the superclass method with an appropriate implementation.
5/25/12

Public versus private members

A class's public members are accessible wherever the program has a 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.

5/25/12

protected Members

Using protected access offers an intermediate level of access between public and private.

A superclass's protected members can be accessed by members of that superclass, by members of its subclasses and by members of other classes in the same package (i.e., protected members also have package access).

5/25/12

All public and protected superclass

Software Engineering Observation

Methods 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 (public, protected) methods provided in the superclass and inherited by the subclass.

Declaring private instance variables helps programmers test, debug and 5/25/12

Consider types of employees in a company's payroll application to discuss the relationship between a superclass and its subclass.

Relationship between Superclasses and Subclasses

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 as objects of a subclass) receive a base 5/25/12 salary plus a percentage of their sales.

Class CommissionEmployee

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

5/25/12

Creating a BasePlusCommissionEmployee Class without Using Inheritance

2nd example: class BasePlusCommissionEmployee directly inherits from class Object and declares as private instance variables a 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 class CommissionEmployee.

This example declares and tests (a completely new and independent) class BasePlusCommissionEmployee, which contains a first name, last name, social security number, gross sales amount, commission rate and base salary. Class BasePlusCommissionEmployee's public services include a BasePlusCommissionEmployee constructor and methods earnings and toString. declare public get and set methods for the class's private instance variables firstName, lastName, socialSecurityNumber, grossSales, commissionRate and baseSalary. 5/25/12 variables and methods encapsulate all the necessary These

5/25/12

Software Engineering Observation

Copying 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. inheritance, the common instance

With 5/25/12

Creating a CommissionEmployee BasePlusCommissionEmployee Inheritance Hierarchy 3rd example: declares a separate BasePlusCommissionEmployee2 class that extends class CommissionEmployee (i.e., a BasePlusCommissionEmployee2 is a CommissionEmployee who also has a base salary) and attempts to access class CommissionEmployee's private members. This results in compilation errors, because the subclass cannot access the superclass's private instance variables. 5/25/12

Each subclass constructor must implicitly or explicitly call its superclass constructor to ensure that the instance variables inherited from the superclass are initialized properly.

BasePlusCommissionEmployee2's sixargument constructor explicitly calls class CommissionEmployee's fiveargument constructor to initialize the superclass portion of a BasePlusCommissionEmployee2 object.

BasePlusCommissionEmployee2's sixargument constructor invokes the 5/25/12 CommissionEmployee's five-argument

5/25/12

5/25/12

CommissionEmployeeBasePlusCommiss ionEmployee Inheritance Hierarchy Using protected Instance Variables

4th example: we show that if CommissionEmployee's instance variables are declared as protected, a BasePlusCommissionEmployee3 class that extends class CommissionEmployee2 can access that data directly.

5/25/12

declare class CommissionEmployee2 with protected instance variables.

CommissionEmployeeBasePlusCo mmissionEmployee Inheritance Hierarchy Using protected Instance Variables

A superclass's protected members are inherited by all subclasses of that superclass.

Class CommissionEmployee2 is a modification of class CommissionEmployee that declares instance variables firstName, lastName, socialSecurityNumber, grossSales and commissionRate as protected rather than private.

5/25/12

Class BasePlusCommissionEmployee3 does not inherit class CommissionEmployee2's constructor. However, class BasePlusCommissionEmployee3's six-argument constructor calls class CommissionEmployee2's fiveargument constructor explicitly.
BasePlusCommissionEmployee3's 5/25/12

six-

5/25/12

5/25/12

STOP HERE

5/25/12

In this example, we declared superclass instance variables as protected so that subclasses could inherit them. Inheriting protected instance variables slightly increases performance, because we can directly access the variables in the subclass without incurring the overhead of a set or get method call. 5/25/12

Software Engineering Observation

The Java compiler sets the superclass of a class to Object when the class declaration does not explicitly extend a superclass. It is a syntax error to override a method with a more restricted access modifier.

Common Programming Error

A public method of the superclass cannot become a protected or private 5/25/12

Programming Tips

Constructors are not inherited,

so class CommissionEmployee does not inherit class Object's constructor. However, class CommissionEmployee's constructor calls class Object's constructor implicitly.

the first task of any subclass constructor is to call its direct superclass's constructor, either explicitly or implicitly (if no constructor call is specified), to 5/25/12 ensure that the instance variables

Problems with protected instance variables

Using protected instance variables creates several potential problems.


First, the subclass object can set an inherited variable's value directly without using a set method. Therefore, a subclass object can assign an invalid value to the variable, thus leaving the object in an inconsistent state. For example, if we were to declare CommissionEmployee3's instance variable grossSales as protected, a 5/25/12 subclass object (e.g.,

Software Engineering Observation

Use 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.

Software Engineering Observation


Declaring superclass instance variables private (as opposed to protected) enables the superclass implementation 5/25/12 of these instance variables to change

5th example: sets the CommissionEmployee instance variables back to private in class CommissionEmployee3 to enforce good software engineering. Then we show how a separate BasePlusCommissionEmployee4 class, which extends class CommissionEmployee3, can use CommissionEmployee3's public 5/25/12 methods to manipulate

CommissionEmployeeBasePlusCommiss ionEmployee Inheritance Hierarchy Using private Instance Variables

Lets now use the best software engineering practices.

Class CommissionEmployee3 declares all instance variables as private and provides some public methods (see method list below) for manipulating these values. methods earnings and toString use instance variables: methods to obtain the the class's get firstName, lastName, socialSecurityNumber, grossSales and commissionRate values of its instance variables. methods: setFirstName, getFirstName, setLastName,
getLastName, setSocialSecurityNumber, getSocialSecurityNumber,

5/25/12 If we decide to change the instance variable setGrossSales, getGrossSales, setCommissionRate, getCommissionRate,

Class BasePlusCommissionEmployee4 has several changes to its method implementations that distinguish it from class BasePlusCommissionEmployee3.
Methods earnings and toString each invoke method getBaseSalary to obtain the base salary value, rather than accessing baseSalary directly. If we 5/25/12 decide to rename instance variable

BasePlusCommissionEmployee4's toString method overrides class CommissionEmployee3's toString method to return a string representation that is appropriate for a base-salaried commission employee. The new version creates part of a BasePlusCommissionEmployee4 object's string representation (i.e., the string "commission employee" and the values of class CommissionEmployee3's private instance variables) by calling 5/25/12

Software Engineering Observation:

if a method performs all or some of the actions needed by another method, call that method rather than duplicate its code. By having BasePlusCommissionEmployee4's earnings method invoke CommissionEmployee3's earnings method to calculate part of a BasePlusCommissionEmployee4 object's earnings, we avoid duplicating the code and reduce code-maintenance problems.

Common Programming Error


When a superclass method is overridden in a subclass, the subclass version often calls the superclass version to do a portion of the work. 5/25/12

Conclusion

In this section, we have shown you an evolutionary set of examples that was carefully designed to teach key capabilities for good software engineering with inheritance. You learned

how to use the keyword extends to create a subclass using inheritance

how to use protected superclass members to enable a subclass to access 5/25/12

Constructors in Subclasses

Instantiating a subclass object begins a chain of constructor calls in which the subclass constructor, before performing its own tasks, invokes its direct superclass's constructor either explicitly (via the super reference) or implicitly (calling the superclass's default constructor or no-argument constructor).
5/25/12

Similarly, if the superclass is derived

Software Engineering Observation


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 5/25/12 variables. Java ensures that even if a

Our next example declares a

CommissionEmployee4 class containing the same features as CommissionEmployee.

The constructor is modified to output text upon its invocation. BasePlusCommissionEmployee5 class is almost identical to BasePlusCommissionEmployee4, except 5/25/12

Orders of Constructor Execution

5/25/12

Orders of Constructor Execution

Class ConstructorTest demonstrates the order in which constructors are called for objects of classes that are part of an inheritance hierarchy.

Method main begins by instantiating CommissionEmployee4 object employee1.

instantiate BasePlusCommissionEmployee5 object employee2. This invokes the 5/25/12 CommissionEmployee4 constructor,

Software Engineering with Inheritance

When a new class extends an existing class, the new class inherits the 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. Doing this does not require the subclass programmer to change the superclass's 5/25/12

Sometimes, students have difficulty appreciating the scope of the problems faced by designers who work on large-scale software projects in industry. People experienced with such projects say that effective software reuse improves the software development process. Objectoriented programming facilitates software reuse, potentially 5/25/12 shortening development time.

Object Class

All classes in Java inherit directly or indirectly from the Object class (package java.lang), so its 11 methods are inherited by all other classes. Figure 9.18 summarizes Object's methods.

5/25/12

Object methods that are inherited 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 on which it is called. When cloning is required for objects of a class, the class should override method clone as a public method and should implement interface Cloneable (package java.lang). The default implementation of this method performs a so-called shallow 5/25/12 copyinstance variable values in one

Equals

5/25/12

This method compares two objects for equality and returns TRue if they are equal and false otherwise. The method takes any Object as an argument. When objects of a particular class must be compared for equality, the class should override method equals to compare the contents of the two objects. The method's implementation should meet the following requirements:

finalize
This protected method is called by the garbage collector to perform termination housekeeping on an object just before the garbage collector reclaims the object's memory. It is not guaranteed that the garbage collector will reclaim an object, so it cannot be guaranteed that the object's finalize method will execute. The method must specify an empty parameter list and must return 5/25/12 void. The default implementation of this

hashCode
A hashtable is a data structure (discussed in Section 19.10) that relates one object, called the key, to another object, called the value. When initially inserting a value into a hashtable, the key's hashCode method is called. The hashcode value returned is used by the hashtable to determine the location at which to insert the corresponding value. The key's hashcode is also used by the 5/25/12 hashtable to locate the key's

toString

This method returns a String representation of an object. The default implementation of this method returns the package name and class name of the object's class followed by a hexadecimal representation of the value returned by the object's hashCode method.

5/25/12

Software Engineering Observation 9.10


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 5/25/12 from the superclass.

You might also like