inheritance and polymorphism

40
Inheritance and Polymorphism

Upload: odina

Post on 22-Feb-2016

41 views

Category:

Documents


0 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Inheritance and Polymorphism

Inheritance and Polymorphism

Page 2: 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.

Page 3: Inheritance and Polymorphism

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

Page 4: Inheritance and Polymorphism

InheritanceTo 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

entities2. Define classes as an extension of common class inheriting

everything form the common class

Notes : Common class = superclass, ancestor, base classClass inherit = subclasses ; descendant; derived class

Page 5: Inheritance and Polymorphism

Examples

Superclass Subclasses Student GraduateStudent, UndergraduateStudent Shape Circle, Triangle, Rectangle Loan CarLoan, HomeImprovementLoan,

MortgageLoan Employee Faculty, Staff BankAccount CheckingAccount, SavingsAccount

Page 6: Inheritance and Polymorphism

ExampleEmployee

+name : String+salary : double+birthDate : Date

+getDetails () : String

public class Manager{ public String name; public double salary; public Date birthDate; public String department;

public void getDetail(){ //... }

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(){ //... }

Page 7: Inheritance and Polymorphism

Inheritance ConceptEmployee

Manager

+name : String+salary : double+birthDate : Date

+getDetails () : String

+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

Page 8: Inheritance and Polymorphism

Inheritance Syntaxpublic class Employee{ public String name; public double salary; public Date birthDate;

public void getDetail(){ //... }

public class Manager extends Employee{ public String department;}

Employee

Manager

+name : String+salary : double+birthDate : Date

+getDetail () : String

+department : String<modifier> class <className> extends <superclass> {

// <declaration>}

Page 9: Inheritance and Polymorphism

Employee

EngineerManager

Director

+ carAllowance : double

+ inceaseAllowance()

name : Stringsalary : doublebirthDate : Date

getDetail () : String

Inheritance Tree

+department : String

Page 10: Inheritance and Polymorphism

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.

Page 11: Inheritance and Polymorphism

Type of Student Grading System Undergraduate pass if (test1+test2+test3/3) >=70Graduate pass if (test1+test2+test3/3) >=80

Steps:1. Define two unrelated classes for undergraduate and graduate students2. Define entities that share common data or behavior (avoid duplication)3. Design these two classes using inheritance4. 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)

Defining Classes with Inheritance

Page 12: Inheritance and Polymorphism

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.

Page 13: Inheritance and Polymorphism

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.

Page 14: Inheritance and Polymorphism

Inheritance Hierarchy

Page 15: Inheritance and Polymorphism

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.

Page 16: Inheritance and Polymorphism

Inheritance and Member Accessibility• We use the following visual representation of

inheritance to illustrate data member accessibility.

Class Hierarchy

This shows the inheritedcomponents of the superclass are part ofthe subclass instance

Instances

Page 17: Inheritance and Polymorphism

The Effect of Three Visibility Modifiers

Page 18: Inheritance and Polymorphism

Accessibility of Super from Sub• Everything except the private members of the Super class is

visible from a method of the Sub class.

Page 19: Inheritance and Polymorphism

Accessibility from Another Instance

• Data members accessible from an instance are also accessible from other instances of the same class.

Page 20: Inheritance and Polymorphism

AccessibilityModifier Same

classSame

PackageSubclass Universe

private Yes

default Yes Yes

protected Yes Yes Yes

public Yes Yes Yes Yes

Page 21: Inheritance and Polymorphism

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.

Page 22: Inheritance and Polymorphism

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.

Page 23: Inheritance and Polymorphism

Overriding Method

public class Employee{ // class nameprivate 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; }

}

Page 24: Inheritance and Polymorphism

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.

Page 25: Inheritance and Polymorphism

Example class definition:class Person { // class name

public void sayHello(){ // method declaration System.out.println (“ hello guys !”); }

}Is equivalent toclass Person { // class name

public Person (){ super ();} public void sayHello(){ System.out.println (“ hello guys !”);}

}

This statement calls the superclass’s constructor

Automatically added to the classes by compiler

Inheritance & Constructor

Page 26: Inheritance and Polymorphism

Example 2 : constructor definition:class MyClass { // class name

private int myInt; public myClass(){ // method declaration myInt = 10; }

}Compiler will rewrite the constructor toclass MyClass { // class name

public MyClass (){ Super (); myInt = 10;}

}

Automatically added to the classes by compiler

Inheritance & Constructor

Page 27: Inheritance and Polymorphism

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.

Inheritance & Constructor

Page 28: Inheritance and Polymorphism

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

Page 29: Inheritance and Polymorphism

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();

Page 30: Inheritance and Polymorphism

• 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();

Page 31: Inheritance and Polymorphism

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();. . .

Page 32: Inheritance and Polymorphism

State of the roster Array

• The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes.

Page 33: Inheritance and Polymorphism

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.

Page 34: Inheritance and Polymorphism

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++;

}}

Page 35: Inheritance and Polymorphism

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.

Page 36: Inheritance and Polymorphism

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() ;}

Page 37: Inheritance and Polymorphism

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.

Page 38: Inheritance and Polymorphism

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.

Page 39: Inheritance and Polymorphism

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.

Page 40: Inheritance and Polymorphism

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.