comp 249 programming methodology chapter 7 - inheritance – part a dr. aiman hanna department of...
TRANSCRIPT
Comp 249 Programming Methodology Chapter 7 - Inheritance – Part A
Dr. Aiman HannaDepartment of Computer Science & Software Engineering
Concordia University, Montreal, Canada
These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by
Pearson Education / Addison-Wesley.
Copyright © 2007-2013 Pearson Addison-WesleyCopyright © 2010-2013 Aiman Hanna
All rights reserved
Introduction to Introduction to InheritanceInheritance
InheritanceInheritance is one of the main techniques is one of the main techniques of object-oriented programming (OOP)of object-oriented programming (OOP)
Using this technique, further classes can Using this technique, further classes can be created from existing ones; those be created from existing ones; those classes are said to classes are said to inheritinherit the methods the methods and instance variables of the class they and instance variables of the class they inheritedinherited The new class is called a The new class is called a derived classderived class The original class is called the The original class is called the base classbase class
Advantage: Reusing existing code Advantage: Reusing existing code
7-2
Derived ClassesDerived Classes
When designing certain classes, there is When designing certain classes, there is often a natural hierarchy for grouping often a natural hierarchy for grouping themthem For instance, for the employees of a company, For instance, for the employees of a company,
there are hourly employees and salaried there are hourly employees and salaried employeesemployees
Hourly employees can be divided into full time Hourly employees can be divided into full time and part time workersand part time workers
Salaried employees can be divided into those Salaried employees can be divided into those on technical staff, and those on the executive on technical staff, and those on the executive staffstaff
7-3
Derived ClassesDerived Classes Since an hourly employee is an employee, Since an hourly employee is an employee,
it is defined as a it is defined as a derived derived class of the class class of the class EmployeeEmployee A A derived classderived class is defined by adding instance is defined by adding instance
variables and methods to an existing classvariables and methods to an existing class The existing class that the derived class is The existing class that the derived class is
built upon is called the built upon is called the base classbase class The phrase The phrase extends BaseClassextends BaseClass must be must be
added to the derived class definition:added to the derived class definition: public class HourlyEmployee extends Employeepublic class HourlyEmployee extends Employee
See Inherit1.javaSee Inherit1.java
7-5
Derived ClassesDerived Classes Derived classes (also referred to as Derived classes (also referred to as
subclassessubclasses)) inherit all instance variables and inherit all instance variables and methods of the base class (also referred to as methods of the base class (also referred to as superclasssuperclass). ).
Any object of a derived class can invoke one of these Any object of a derived class can invoke one of these parent methods, just like any of its own methodsparent methods, just like any of its own methods
The derived class can add more instance variables, The derived class can add more instance variables, static variables, and/or methodsstatic variables, and/or methods
See Inherit2.javaSee Inherit2.java
7-6
Parent and Child ClassesParent and Child Classes
A base class is often called the A base class is often called the parent parent classclass A derived class is then called a A derived class is then called a child classchild class
These relationships are often extended These relationships are often extended such that a class that is a parent of a such that a class that is a parent of a parent . . . of another class is called an parent . . . of another class is called an ancestor classancestor class If class If class AA is an ancestor of class is an ancestor of class BB, then class , then class BB
can be called a can be called a descendentdescendent of class of class AA
7-7
Overriding a Method Overriding a Method DefinitionDefinition
Although a derived class inherits Although a derived class inherits methods from the base class, it can methods from the base class, it can change or change or override override an inherited an inherited method if necessarymethod if necessary In order to override a method definition, In order to override a method definition,
a new definition of the method is simply a new definition of the method is simply placed in the class definition, just like placed in the class definition, just like any other method that is added to the any other method that is added to the derived classderived class
See Inherit3.javaSee Inherit3.java7-8
Changing the Return Type Changing the Return Type of an Overridden Methodof an Overridden Method
Ordinarily, the type returned may not be Ordinarily, the type returned may not be changed when overriding a method changed when overriding a method
However, if it is a class type, then the However, if it is a class type, then the returned type may be changed to that of returned type may be changed to that of any descendent class of the returned typeany descendent class of the returned type
This is known as a This is known as a covariant return typecovariant return type Covariant return types Covariant return types are new in Java 5.0; are new in Java 5.0;
they are not allowed in earlier versions of Javathey are not allowed in earlier versions of Java
7-9
Covariant Return TypeCovariant Return Type
Given the following base class:Given the following base class:public class BaseClasspublic class BaseClass{ . . .{ . . . public Employee getSomeone(int someKey)public Employee getSomeone(int someKey) . . .. . .
The following is allowed in Java The following is allowed in Java 5.0:5.0:public class DerivedClass extends BaseClasspublic class DerivedClass extends BaseClass{ . . .{ . . . public HourlyEmployee getSomeone(int someKey)public HourlyEmployee getSomeone(int someKey) . . .. . .
7-10
Changing the Access Permission of Changing the Access Permission of an Overridden Methodan Overridden Method
The access permission of an overridden The access permission of an overridden method can be changed from private in method can be changed from private in the base class to public (or some other the base class to public (or some other more permissive access) in the derived more permissive access) in the derived classclass
However, the access permission of an However, the access permission of an overridden method can not be changed overridden method can not be changed from public in the base class to a more from public in the base class to a more restricted access permission in the restricted access permission in the derived classderived class
7-11
Changing the Access Permission of Changing the Access Permission of an Overridden Methodan Overridden Method
Given the following method header in a base case:Given the following method header in a base case:private void doSomething()private void doSomething()
The following method header is valid in a derived The following method header is valid in a derived class:class:public void doSomething()public void doSomething()
However, the opposite is not validHowever, the opposite is not valid Given the following method header in a base case:Given the following method header in a base case:
public void doSomething()public void doSomething() The following method header is The following method header is notnot valid in a valid in a
derived class:derived class: private void doSomething()private void doSomething()
7-12
Pitfall: Overriding Versus Pitfall: Overriding Versus OverloadingOverloading
Do not confuse Do not confuse overridingoverriding with with overloadingoverloading When a method is overridden, the new When a method is overridden, the new
method definition given in the derived class method definition given in the derived class has the exact same number and types of has the exact same number and types of parameters as in the base classparameters as in the base class
When a method in a derived class has a When a method in a derived class has a different signature from the method in the different signature from the method in the base class, that is overloadingbase class, that is overloading
Note that when the derived class overloads Note that when the derived class overloads the original method, it still inherits the the original method, it still inherits the original method from the base class as welloriginal method from the base class as well
7-13
The The finalfinal Modifier Modifier
If the modifier If the modifier finalfinal is placed before is placed before the definition of a the definition of a methodmethod, then that , then that method may not be overridden in a method may not be overridden in a derived classderived class
It the modifier It the modifier finalfinal is placed before is placed before the definition of a the definition of a classclass, then that , then that class may not be used as a base class class may not be used as a base class to derive other classesto derive other classes
See Inherit4.javaSee Inherit4.java
7-14
The The supersuper Constructor Constructor A derived class uses a constructor from the base class A derived class uses a constructor from the base class
to initialize all the data inherited from the base classto initialize all the data inherited from the base class In order to invoke a constructor from the base In order to invoke a constructor from the base
class, it uses a special syntax:class, it uses a special syntax: public derivedClass(int p1, int p2, double p3) public derivedClass(int p1, int p2, double p3)
{{ super(p1, p2);super(p1, p2); instanceVariable = p3;instanceVariable = p3; }}
In the above example, In the above example, super(p1, p2);super(p1, p2); is a call to is a call to the base class constructorthe base class constructor
See Inherit5.javaSee Inherit5.java
7-15
The The supersuper Constructor Constructor A call to the base class constructor can never use the A call to the base class constructor can never use the
name of the base class, but uses the keyword name of the base class, but uses the keyword supersuper insteadinstead
A call to A call to supersuper must always be the first action taken in must always be the first action taken in a constructor definitiona constructor definition
Notice that if Notice that if super super is not used, then a call to the is not used, then a call to the default constructor of the base class is automatically default constructor of the base class is automatically issuedissued
Consequently, a compilation error would occur if the Consequently, a compilation error would occur if the base class has no default constructorbase class has no default constructor
See Inherit6.javaSee Inherit6.java See Inherit7.javaSee Inherit7.java
7-16
The The thisthis Constructor Constructor Within the definition of a constructor for a Within the definition of a constructor for a
class, class, thisthis can be used as a name for can be used as a name for invoking another constructor of the same invoking another constructor of the same classclass The same restrictions on how to use a call to The same restrictions on how to use a call to supersuper
apply to the apply to the thisthis constructor constructor If it is necessary to include a call to both If it is necessary to include a call to both supersuper and and thisthis, the call using , the call using thisthis must be must be made first, and then the constructor that is made first, and then the constructor that is called must call called must call supersuper as its first action as its first action
See Inherit8.javaSee Inherit8.java
7-17
The The thisthis Constructor Constructor Often, a no-argument constructor uses Often, a no-argument constructor uses thisthis to to
invoke an explicit-value constructorinvoke an explicit-value constructor No-argument constructor (invokes explicit-value No-argument constructor (invokes explicit-value
constructor using constructor using thisthis and default arguments): and default arguments):public ClassName()public ClassName(){{ this(argument1, argument2);this(argument1, argument2);}}
Explicit-value constructor (receives default values):Explicit-value constructor (receives default values):public ClassName(public ClassName(type1type1 param1, param1, type2type2 param2) param2){{ . . .. . .}}
7-18
The The thisthis Constructor Constructor
Example:Example:public HourlyEmployee()public HourlyEmployee(){{ this("No name", new Date(), 0, 0);this("No name", new Date(), 0, 0);}}
The above constructor will cause the The above constructor will cause the constructor with the following heading to constructor with the following heading to be invoked:be invoked:public HourlyEmployee(String theName, public HourlyEmployee(String theName, Date theDate, double theWageRate, Date theDate, double theWageRate, double theHours)double theHours)
7-19
Tip: An Object of a Derived Class Tip: An Object of a Derived Class Has More than One TypeHas More than One Type
An object of a derived class has the type of the derived class, An object of a derived class has the type of the derived class, and it also has the type of the base classand it also has the type of the base class
More generally, an object of a derived class has the type of More generally, an object of a derived class has the type of every one of its ancestor classesevery one of its ancestor classes Therefore, an object of a derived class can be assigned to a Therefore, an object of a derived class can be assigned to a
variable of any ancestor typevariable of any ancestor type An object of a derived class can be plugged in as a parameter An object of a derived class can be plugged in as a parameter
in place of any of its ancestor classesin place of any of its ancestor classes In fact, a derived class object can be used anyplace that an In fact, a derived class object can be used anyplace that an
object of any of its ancestor types can be usedobject of any of its ancestor types can be used Note, however, that this relationship does not go the other wayNote, however, that this relationship does not go the other way
An ancestor type can never be used in place of one of its An ancestor type can never be used in place of one of its derived typesderived types
See Inherit9.javaSee Inherit9.java
7-20
Pitfall: The Terms "Subclass" and Pitfall: The Terms "Subclass" and "Superclass""Superclass"
The terms The terms subclasssubclass and and superclasssuperclass are are sometimes mistakenly reversedsometimes mistakenly reversed A superclass or base class is more general and A superclass or base class is more general and
inclusive, but less complexinclusive, but less complex A subclass or derived class is more A subclass or derived class is more
specialized, less inclusive, and more complexspecialized, less inclusive, and more complex As more instance variables and methods are added, As more instance variables and methods are added,
the number of objects that can satisfy the class the number of objects that can satisfy the class definition becomes more restricteddefinition becomes more restricted
7-21