Chapter07 & 08-Inheritance & Polymorphism

Download Report

Transcript Chapter07 & 08-Inheritance & Polymorphism

Inheritance and
Polymorphism
Objectives
– Define inheritance, overriding methods and
polymorphism.
– Define reusable classes based on inheritance and
abstract classes and abstract methods.
– Define methods, using the protected modifier.
– Describe the concepts of constructor in
inheritance.
– Write programs that are easily extensible and
modifiable by applying polymorphism in program
design.
Inheritance
• Inheritance
– Software reusability
– Create new class from existing class
• Absorb existing class’s data and behaviors
• Enhance with new capabilities
– Subclass extends superclass
• Subclass
– More specialized group of objects
– Behaviors inherited from superclass
» Can customize
– Additional behaviors
Inheritance
To design two or more entities that are different but share
many common features.
Steps :
1. Define a class that contains the common feature of the
entities
2. Define classes as an extension of common class inheriting
everything form the common class
Notes :
Common class = superclass, ancestor, base class
Class inherit = subclasses ; descendant; derived class
Examples
Superclass
Subclasses
Student
GraduateStudent, UndergraduateStudent
Shape
Circle, Triangle, Rectangle
Loan
CarLoan, HomeImprovementLoan,
MortgageLoan
Employee
Faculty, Staff
BankAccount
CheckingAccount, SavingsAccount
Example
Employee
+name : String
+salary : double
+birthDate : Date
+getDetails () : String
Manager
+name : String
+salary : double
+birthDate : Date
+department : String
+getDetails () : String
public class Employee{
public String name;
public double salary;
public Date birthDate;
public void getDetail(){
//...
}
public class Manager{
public String name;
public double salary;
public Date birthDate;
public String department;
public void getDetail(){
//...
}
Inheritance Concept
Employee
+name : String
+salary : double
+birthDate : Date
+getDetails () : String
Manager
+department : String
Java programming language
allows a class to extend only one
other class
When a class inherits from only
one class, it is called single
inheritance
For multiple inheritance (inherits
more than one classes) must used
interfaces
Inheritance Syntax
Employee
+name : String
+salary : double
+birthDate : Date
+getDetail () : String
Manager
public class Employee{
public String name;
public double salary;
public Date birthDate;
public void getDetail(){
//...
}
public class Manager extends Employee{
public String department;
}
+department : String
<modifier> class <className> extends <superclass>
{
// <declaration>
}
Employee
name : String
salary : double
birthDate : Date
Inheritance
Tree
getDetail () : String
Manager
Engineer
+department : String
Director
+ carAllowance : double
+ inceaseAllowance()
Another example
• Case Study:
– Suppose we want implement a class roster that
contains both undergraduate and graduate
students.
– Each student’s record will contain his or her name,
three test scores, and the final course grade.
– The formula for determining the course grade is
different for graduate students than for
undergraduate students.
Defining Classes with Inheritance
Type of Student Grading System
Undergraduate
Graduate
pass if (test1+test2+test3/3) >=70
pass if (test1+test2+test3/3) >=80
Steps:
1. Define two unrelated classes for undergraduate and graduate students
2. Define entities that share common data or behavior (avoid duplication)
3. Design these two classes using inheritance
4. Define 3 classes
1. Student (class to incorporate behavior and data common to both
graduate and undergraduate
2. GraduateStudents (class to incorporate behavior specific to graduate
students)
3. UndergraduateStudents (class to incorporate behavior specific to
undergraduate students)
Modeling Two Types of Students
• There are two ways to design the classes to
model undergraduate and graduate students.
– We can define two unrelated classes, one for
undergraduates and one for graduates.
– We can model the two kinds of students by using
classes that are related in an inheritance
hierarchy.
• Two classes are unrelated if they are not
connected in an inheritance relationship.
Classes for the Class Roster
• For the Class Roster sample, we design three classes:
– Student
– UndergraduateStudent
– GraduateStudent
• The Student class will incorporate behavior and data common
to both UndergraduateStudent and GraduateStudent
objects.
• The UndergraduateStudent class and the GraduateStudent
class will each contain behaviors and data specific to their
respective objects.
Inheritance Hierarchy
The Protected Modifier
• The modifier protected makes a data member or
method visible and accessible to the instances of
the class and the descendant classes.
• Intermediate level of protection between
public and private.
• Public data members and methods are accessible
to everyone.
• Private data members and methods are
accessible only to instances of the class.
Inheritance and Member Accessibility
• We use the following visual representation of
inheritance to illustrate data member accessibility.
Instances
This shows the inherited
components of the
superclass are part of
the subclass instance
Class Hierarchy
The Effect of Three Visibility Modifiers
Accessibility of Super from Sub
• Everything except the private members of the Super class is
visible from a method of the Sub class.
Accessibility from Another Instance
• Data members accessible from an instance are also accessible
from other instances of the same class.
Accessibility
Modifier
Same
class
Same
Package
Subclass
private
Yes
default
Yes
Yes
protected
Yes
Yes
Yes
public
Yes
Yes
Yes
Universe
Yes
Overriding Method
• A subclass can modify behavior inherited form parent class
• A subclass can create a method with different functionality
than the parent’s method but with the same:
> name
> return type
> argument list
• Overriding is to adding additional features; modify existing
behavior.
Rules About Overriding Method
• Must have a return types that is identical to the method it
overrides
• Cannot be less accessible that the method it overrides.
• When override a method, real goal is not to replace the
existing behavior but to extend that behavior in some way.
• Can used super keyword – refers to the superclass of the
class in which the keyword is used. It is used to refer to the
member variables or methods of the superclass.
Overriding Method
public class Employee{ // class name
private String name;
private double salary;
public String getDetail(){ // method declaration
return “ Name : “+ name “\n” +
“ Salary : “ +salary;
}
}
public class Manager extends Employee{ // class name
private String department;
public String getDetail(){
return super.getDetails() + //invoked the entire behavior
“ Manager of : “ + department;
}
}
Inheritance and Constructors
• Unlike members of a superclass, constructors of a superclass are
not inherited by its subclasses.
• You must define a constructor for a class or use the default
constructor added by the compiler.
• The statement
super();
calls the superclass’s constructor.
• If the class declaration does not explicitly designate the
superclass with the extends clause, then the class’s superclass is
the Object class.
Inheritance & Constructor
Example class definition:
class Person { // class name
public void sayHello(){ // method declaration
System.out.println (“ hello guys !”);
}
}
Is equivalent to
class Person { // class name
Automatically
added to the
classes by
compiler
}
This statement calls the
superclass’s constructor
public Person (){
super ();
}
public void sayHello(){
System.out.println (“ hello guys !”);
}
Inheritance & Constructor
Example 2 : constructor definition:
class MyClass { // class name
private int myInt;
public myClass(){ // method declaration
myInt = 10;
}
}
Compiler will rewrite the constructor to
class MyClass { // class name
public MyClass (){
Super ();
myInt = 10;
}
}
Automatically added to the
classes by compiler
Inheritance & Constructor
Example 3 :
class Vehicle{ // class name
private String vin;
public Vehicle (String vehicleID){ // constructor declaration
vin = vehicleID;
}
}
class Truck extends Vehicle{ // class name
private int cargoWeightLimit;
public Truck (int weightLimit, String vin){
super (vin);
cargoWeightLimit = weightLimit;
}
}
Notes : If a class has a superclass that is not the Object class, then a constructor of the class
should make an explicit call to a constructor of the superclass.
Case study – Company Payroll
Application
• Commission employee are paid a percentage of their sales
• Base-salaried commission employee receives a base salary plus
percentage of their sales.
• Commission employee has first name, last name, social security
number, commission rate and gross (total) sales amount.
• Base-salaried commission employee has first name, last name,
social security number, commission rate, gross (total) sales
amount and base salary
Polymorphism
• Polymorphism comes from Greek meaning “many forms.”
• Polymorphism allows a single variable to refer to objects
from different subclasses in the same inheritance hierarchy
• For example, if Cat and Dog are subclasses of Pet, then the
following statements are valid:
Pet myPet;
myPet = new Dog();
. . .
myPet = new Cat();
• This is another example.
• If Graduate Student and Undergraduate Student
are subclasses of Student, then the following
statements are valid:
Student student;
student = new Student();
student = new GraduateStudent();
. . .
student = new UndergraduateStudent();
Creating the roster Array
• We can also declare using array. Instead of using two separate array to
represent both Graduate and Undergraduate Student, we can declare single
array for them.
• It is because the array elements are objects.
• We can maintain our class roster using an array, combining objects from the
Student, UndergraduateStudent, and GraduateStudent classes.
Student roster = new Student[40];
. . .
roster[0] = new GraduateStudent();
roster[1] = new UndergraduateStudent();
roster[2] = new UndergraduateStudent();
. . .
State of the roster Array
• The roster array with elements referring to instances of
GraduateStudent or UndergraduateStudent classes.
Sample Polymorphic Message
• To compute the course grade using the roster array, we execute
for (int i = 0; i < numberOfStudents; i++) {
roster[i].computeCourseGrade();
}
• If roster[i] refers to a GraduateStudent, then the
computeCourseGrade method of the GraduateStudent
class is executed.
• If roster[i] refers to an UndergraduateStudent, then the
computeCourseGrade method of the
UndergraduateStudent class is executed.
The instanceof Operator
• The instanceof operator can help us learn the
class of an object.
• The following code counts the number of
undergraduate students.
int undergradCount = 0;
for (int i = 0; i < numberOfStudents; i++) {
if ( roster[i] instanceof UndergraduateStudent ) {
undergradCount++;
}
}
Abstract Superclasses and Abstract
Methods
• When we define a superclass, we often do not
need to create any instances of the superclass.
• Depending on whether we need to create
instances of the superclass, we must define
the class differently.
• We will study examples based on the Student
superclass defined earlier.
Definition: Abstract Class
• An abstract class is a class
–
–
–
–
defined with the modifier abstract OR
that contains an abstract method OR
that does not provide an implementation of an inherited abstract method
that is not intended to be used to create objects.
• An abstract method is a method with the keyword abstract, and
it ends with a semicolon instead of a method body.
– Private methods and static methods may not be declared abstract.
abstract class Student{
……
abstract public void computeCourseGrades() ;
}
Case 1
• Student Must Be Undergraduate or Graduate
– If a student must be either an undergraduate or a
graduate student, we only need instances of
UndergraduateStudent or GraduateStudent.
– Therefore, we must define the Student class so
that no instances may be created of it.
Case 2
• Student Does Not Have to Be Undergraduate
or Graduate.
• In this case, we may design the Student class
in one of two ways.
– We can make the Student class instantiable.
– We can leave the Student class abstract and add a
third subclass, OtherStudent, to handle a student
who does not fall into the UndergraduateStudent
or GraduateStudent categories.
Which Approach to Use
• The best approach depends on the particular
situation.
• When considering design options, we can ask
ourselves which approach allows easier
modification and extension.
Inheritance versus Interface
• The Java interface is used to share common behavior (only
method headers) among the instances of different
classes.Example : class Person that implements multiple
interfaces such as Driver, Commuter and Biker.
• Inheritance is used to share common code (including both
data members and methods) among the instances of related
classes.
• In your program designs, remember to use the Java interface
to share common behavior. Use inheritance to share
common code.
• If an entity A is a specialized form of another entity B, then
model them by using inheritance. Declare A as a subclass of
B.