0% found this document useful (0 votes)
12 views

Chapter 9 Inheritance - Completer

The document discusses inheritance in object-oriented programming. It defines inheritance as establishing commonalities between classes by creating subclasses that inherit members from superclasses. This allows code reuse and establishing an "is-a" relationship between classes in a hierarchy. The document provides examples of inheritance between classes like shapes and payroll employee types. It also discusses access modifiers, overriding methods, and the toString() method.

Uploaded by

Noor Alnaser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Chapter 9 Inheritance - Completer

The document discusses inheritance in object-oriented programming. It defines inheritance as establishing commonalities between classes by creating subclasses that inherit members from superclasses. This allows code reuse and establishing an "is-a" relationship between classes in a hierarchy. The document provides examples of inheritance between classes like shapes and payroll employee types. It also discusses access modifiers, overriding methods, and the toString() method.

Uploaded by

Noor Alnaser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Inheritance

Ms. Haneen Hijazi

Ms. Haneen Hijazi 1


What is inheritance?
• Inheritance establishes commonalities of your classes (subclasses)
• Commonality expressed in the members of the superclass.
• Create a new class (subclass) from an existing class (superclass)
• Reuse existing class’s members
• possibly embellishing them with new or modified capabilities.
• proven and debugged high-quality (existing) software
• Reduce development time
• Effectively implemented and maintainable systems.
• the new class should inherit the members of an existing class.
• Existing class is the superclass
• New class is the subclass
• A subclass can add its own fields and methods.
• A subclass is more specific than its superclass and represents a more specialized group of objects.
• The subclass exhibits the behaviors of its superclass and can add behaviors that are specific to the subclass.
• This is why inheritance is sometimes referred to as specialization.
• Superclasses tend to be “more general” and subclasses “more specific.”
• A subclass can be a superclass of future subclasses.
• Class hierarchy

Ms. Haneen Hijazi 2


Examples

Ms. Haneen Hijazi 3


inheritance is an “Is-a” relationship
• Is-a: an object of a subclass can also be treated as an object of its
superclass
• Eg: Circle is a Shape
• An object of a circle is an object of a Shape
• one superclass can have many subclasses
• Shape: Superclass
• Rectangle, Circle, Triangle: Subclasses
• → the set of objects represented by a superclass is typically larger
than the set of objects represented by any of its subclasses.

Ms. Haneen Hijazi 4


Inheritance (class) hierarchy
• A superclass exists in a hierarchical relationship with its subclasses.
• Inheritance tree
• Each arrow in the hierarchy represents an is-a relationship.
• Direct superclass
• is the superclass from which the subclass explicitly inherits.
• Indirect superclass
• is any class above the direct superclass in the class hierarchy.
• The Java class hierarchy begins with class Object
• (in package java.lang)
• Every class in Java directly or indirectly extends (or “inherits from”) Object.
• Java supports only single inheritance
• each class is derived from exactly one direct superclass.

Ms. Haneen Hijazi 5


Example 1:
• Inheritance (Generalization)
• Follow the arrows upward in the class hierarchy
• an Employee is a CommunityMember”
• “a Teacher is a Faculty member.”

• CommunityMember
• is the direct superclass of Employee, Student and
Alumnus
• is an indirect superclass of all the other classes in the
diagram.
• Starting from the bottom, you can follow the
arrows and apply the is-a relationship up to the
topmost superclass.

Ms. Haneen Hijazi 6


Example 2

A Triangle is a TwoDimensionalShape and is a Shape


A Sphere is a ThreeDimensionalShape and is a Shape.

Ms. Haneen Hijazi 7


Inheritance vs. Composition
• Not every class relationship is an inheritance relationship.
• Inheritance:
• Is-a relationship
• Reuse existing classes by inheritance
• Composition
• Has-a relationship
• Reuse existing classes by composition
• Example: Person, Employee, Birthdate
• Employee is/has a Person
• Person is/has a Birthdate

Ms. Haneen Hijazi 8


Inheritance Issues
• 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.
• The subclass can override (redefine) the superclass method with an
appropriate implementation.

Ms. Haneen Hijazi 9


Protected 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 within the class itself.
• protected access is an intermediate level of access between public and
private.
• A superclass’s protected members can be accessed by:
• members of that superclass
• members of its subclasses, even in other packages
• members of other classes in the same package
• protected members also have package access.
• All public and protected (and package) superclass members retain their
original access modifier when they become members of the subclass.

Ms. Haneen Hijazi 10


Access super - private member
• A superclass’s private members are hidden from its subclasses
• can be accessed in the subclass only through the public and protected
methods inherited from the superclass
• (And package-access methods in the subclasses in the same package)
• Declaring private instance variables helps you test, debug and
correctly modify systems.
• If a subclass 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.

Ms. Haneen Hijazi 11


Access super – public and protected
• A superclass’s public and protected members are accessible from its
subclasses
• simply by using the member names.

Ms. Haneen Hijazi 12


Access modifiers

Same class Subclass/ Subclass/ Another class/ Another class/


same pack another pack same pack different pack
public Directly/no ref Directly/no ref Directly/no ref Directly/ ref Directly/ ref
protected Directly/no ref Directly/no ref Directly/no ref Directly/ref Indirectly/ ref
default Directly/no ref Directly/no ref Directly/no ref Indirectly/ref Indirectly/ ref
private Directly/no ref indirectly/no ref indirectly/no ref indirectly/ref Indirectly/ ref

Ms. Haneen Hijazi 13


Access public members from the same class and its
subclasses

Accessible, no ref

Ms. Haneen Hijazi 14


Access public members from other classes

Accessible, ref

Ms. Haneen Hijazi 15


Access protected members from the same class and
its subclasses

Directly, no ref
Ms. Haneen Hijazi 16
Access protected members from other classes

Ms. Haneen Hijazi 17


Access default members from the same class
and its subclasses

Ms. Haneen Hijazi 18


Access default members from other classes

Ms. Haneen Hijazi 19


Access private members from the same class

Ms. Haneen Hijazi 20


Access private members from subclasses

Ms. Haneen Hijazi 21


Access private members from other classes

Ms. Haneen Hijazi 22


Example: Payroll Application
• Inheritance hierarchy
• containing types of employees in a company’s payroll application
• Commission employees are paid a percentage of their sales
• Base-salaried commission employees receive a base salary plus a percentage of their sales.

Ms. Haneen Hijazi 23


Ms. Haneen Hijazi 24
Ms. Haneen Hijazi 25
Ms. Haneen Hijazi 26
Ms. Haneen Hijazi 27
Ms. Haneen Hijazi 28
Ms. Haneen Hijazi 29
toString() method
• toString is one of the methods that every class inherits directly or
indirectly from class Object.
• Returns a String representing an object.
• Called implicitly whenever an object must be converted to a String
representation.
• Class Object’s toString method returns a String that includes
the name of the object’s class.
• This is primarily a placeholder that can be overridden by a subclass to specify
an appropriate String representation.

Ms. Haneen Hijazi 30


Overriding Methods
• To override a superclass method, a subclass must declare a method
with the same signature as the superclass method
• @Override annotation
• Indicates that a method should override a superclass method with the same
signature.
• If it does not, a compilation error occurs.
• Though the @override annotation is optional
• declare overridden methods with it to ensure at compilation time that you defined their
signatures correctly.
• It’s always better to find errors at compile time rather than at runtime.

Ms. Haneen Hijazi 31


Overriding a method with a more restricted
access modifier
• It’s a compilation error to override a method with amore restricted access
modifier
• Eg:
• A public superclass method cannot become a protected or private subclass method
• A protected superclass method cannot become a private subclass method.
• Doing so would break the is-a relationship
• which requires that all subclass objects be able to respond to method calls made to
public methods declared in the super-class.
• If 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.

Ms. Haneen Hijazi 32


Example: BasePlusCommissionEmployee
BasePlusCommissionEmployee Vs.
CommissionEmployee
• Much of BasePlusCommissionEmployee’s code is similar, or identical, to that of
CommissionEmployee.
• private instance variables firstName and lastName and methods setFirstName,
getFirstName, setLastName and getLastName are identical.
• Both classes also contain corresponding get and set methods.
• The constructors are almost identical
• BasePlusCommissionEmployee’s constructor also sets the baseSalary.
• The toString methods are almost identical
• BasePlusCommissionEmployee’s toString also outputs instance variable baseSalary
• We literally copied CommissionEmployee’s code, pasted it into
BasePlusCommissionEmployee, then modified the new class to include a
base salary and methods that manipulate the base salary.
• This “copy-and-paste” approach is often error prone and time consuming.
• It spreads copies of the same code throughout a system, creating a code-maintenance
problems—changes to the code would need to be made in multiple classes.

Ms. Haneen Hijazi 40


Solution: use inheritance
• With inheritance, the instance variables and methods that are the
same for all the classes in the hierarchy are declared in a superclass.
• Changes made to these common features in the superclass are inherited by
the subclass.
• Steps:
• Class BasePlusCommissionEmployee class extends class CommissionEmployee
• A BasePlusCommissionEmployee object is a CommissionEmployee
• Inheritance passes on class CommissionEmployee’s capabilities.
• Class BasePlusCommissionEmployee also has instance variable baseSalary.
• Subclass BasePlusCommissionEmployee inherits CommissionEmployee’s instance
variables and methods
• Only CommissionEmployee’s public and protected members are directly accessible in the
subclass.

Ms. Haneen Hijazi 41


Factor out common code

© Copyright 1992-2018 by Pearson Education, Inc. All Rights


Reserved.
Does inheriting a class affect its code?

© Copyright 1992-2018 by Pearson Education, Inc. All Rights


Reserved.
Inheritance and constructors
• Constructors are not inherited.
• The first task of a subclass constructor is to call its direct superclass’s
constructor explicitly or implicitly
• Ensures that the instance variables inherited from the superclass are initialized
properly.
• Explicitly:
• Using super(superclass constructor arguments)
• Must be the first statement in the constructor’s body.
• Implicitly:
• If the code does not include an explicit call to the superclass constructor, Java implicitly calls
the superclass’s default or no-argument constructor.
• You can explicitly use super() to call the superclass’s no-argument or default constructor, but this
is rarely done.
• A class’s default constructor calls the superclass’s default or no-argument
constructor.
Ms. Haneen Hijazi 44
Ms. Haneen Hijazi 45
Ms. Haneen Hijazi 46
Accessing super private members
• Compilation errors occur when the subclass attempts to access the
superclass’s private instance variables.
• Solution:
• Define data field protected
• appropriate get methods to retrieve the values of the superclass’s instance
variables.
• Which is better?
• In most cases, it’s better to use private instance variables to encourage proper
software engineering.
• Code will be easier to maintain, modify and debug.

Ms. Haneen Hijazi 47


Solution 1: CommissionEmployee with protected
instance variables
• Class BasePlusCommissionEmployee extends the new version of class
CommissionEmployee with protected instance variables.
• These variables are now protected members of BasePlusCommissionEmployee.
• If another class extends this version of class BasePlusCommissionEmployee, the
new subclass also can access the protected members.
• With protected instance variables, the subclass gets access to the instance
variables, but classes that are not subclasses and classes that are not in the same
package cannot access these variables directly.

Ms. Haneen Hijazi 48


CommissionEmployeeV2: protected data fields

Ms. Haneen Hijazi 49


Ms. Haneen Hijazi 50
Ms. Haneen Hijazi 51
Extending CommissionEmployee Advantages
• The source code (with inheritance) is considerably shorter than that (without
inheritance)
• Most of the functionality is now inherited from CommissionEmployee
• There is now only one copy of the functionality.
• Code is easier to maintain, modify and debug—the code related to a CommissionEmployee
exists only in that class.

Ms. Haneen Hijazi 52


Problems using protected
• The subclass object can set an inherited variable’s value directly without using a
set method.
• A subclass object can assign an invalid value to the variable
• Subclass methods are more likely to be written so that they depend on the
superclass’s data implementation.
• we may need to modify all the subclasses of the superclass if the superclass implementation
changes.
• Such a class is said to be fragile or brittle, because a small change in the superclass can “break” subclass
implementation.
• Subclasses should depend only on the superclass services and not on the superclass data
implementation.
• You should be able to change the superclass implementation while still providing the same services to
the subclasses.
• If the superclass services change, we must reimplement our subclasses.
• A class’s protected members are visible to all classes in the same package as
the class containing the protected members—this is not always desirable.

Ms. Haneen Hijazi 53


Protected vs. Private

Ms. Haneen Hijazi 54


Solution 2: CommissionEmployee with private
instance variables
• Class CommissionEmployee declares instance variables
firstName, lastName, socialSecurityNumber, grossSales
and commissionRate as private and provides public methods
for manipulating these values.
• Subclass BasePlusCommissionEmployee inherits Commission-
Employee’s non-private methods and can access the private
superclass members via those methods.

Ms. Haneen Hijazi 55


Ms. Haneen Hijazi 56
Ms. Haneen Hijazi 57
Ms. Haneen Hijazi 58
Ms. Haneen Hijazi 59
Ms. Haneen Hijazi 60
CommissionEmployee accesses its private
data using get methods
• CommissionEmployee methods earnings and toString use the class’s
get methods to obtain the values of its instance variables.
• If we decide to change the internal representation of the data (e.g., variable names) only
the bodies of the get and set methods that directly manipulate the instance variables will
need to change.
• These changes occur solely within the superclass-—no changes to the subclass are
needed.
• Localizing the effects of changes like this is a good software engineering practice.

Ms. Haneen Hijazi 61


Ms. Haneen Hijazi 62
Ms. Haneen Hijazi 63
Ms. Haneen Hijazi 64
Invoking super class overridden version from
the overriding version in the subclass
• Good software engineering practice
• If a method performs all or some of the actions needed by another method, call that
method rather than duplicate its code.
• Methods earnings and toString each invoke their superclass versions
and do not access instance variables directly.
• Method earnings overrides class the superclass’s earnings method.
• The new version calls CommissionEmployee’s earnings method with
super.earnings().
• Obtains the earnings based on commission alone
• Placing the keyword super and a dot (.) separator before the superclass
method name invokes the superclass version of an overridden method.

Ms. Haneen Hijazi 65


Ms. Haneen Hijazi 66
Ms. Haneen Hijazi 67
Forget to call using super.

Ms. Haneen Hijazi 68


Constructors in Subclasses
• Instantiating a subclass object begins a chain of constructor calls
• The subclass constructor, before performing its own tasks, explicitly uses super to call
one of the constructors in its direct superclass or implicitly calls the superclass’s default
or no-argument constructor
• If the superclass is derived from another class, the superclass constructor
invokes the constructor of the next class up the hierarchy, and so on.
• The last constructor called in the chain is always Object’s constructor.
• Original subclass constructor’s body finishes executing last.
• Each superclass’s constructor manipulates the superclass instance variables
that the subclass object inherits.

Ms. Haneen Hijazi 69


Initializing instance datafields in Java

Ms. Haneen Hijazi 70


Class Object
• All classes in Java inherit directly or indirectly from class Object, so
its 11 methods are inherited by all other classes.
• Object class methods:

Ms. Haneen Hijazi 71


Equals method

Ms. Haneen Hijazi 72


Ms. Haneen Hijazi 73
Overriding Object equals method

Ms. Haneen Hijazi 74


Ms. Haneen Hijazi 75
Comparing Strings

Ms. Haneen Hijazi 76


getClass() method

Ms. Haneen Hijazi 77


Ms. Haneen Hijazi 78
Ms. Haneen Hijazi 79

You might also like