inheritance & polymorphism - 2

22
Polymorphism & Abstract Class

Upload: prn-usm

Post on 20-May-2015

237 views

Category:

Education


12 download

DESCRIPTION

Chapter 2

TRANSCRIPT

Page 1: Inheritance & Polymorphism - 2

Polymorphism&

Abstract Class

Polymorphism&

Abstract Class

Page 2: Inheritance & Polymorphism - 2

Polymorphism Polymorphism is an object-oriented concept that allows us

to create versatile software designs that deals with multiple objects.

The term polymorphism literally means "having many forms“ – can refer to multiple types of related objects over time in consistence way.

Polymorphism is one of the most elegant uses of inheritance.

A polymorphic reference is a variable that can refer to different types of objects at different points in time. Specifically, a reference variable of a superclass type can refer to any object of its subclasses in the inheritance hierarchy.

Page 3: Inheritance & Polymorphism - 2

Polymorphic Reference For example, if the Animal class is used to derive a

class called Cat, then a Animal reference could be used to point to a Cat object

Similarly, Animal can refer to any of its subclasses

Animal myPet;myPet = new Cat();

Animal

CatRabbitmyPet = new Rabbit();

Page 4: Inheritance & Polymorphism - 2

Another example: UndergraduateStudent and GraduateStudent are subclasses of

Student, the following statements are valid:

Student stud1 = new Student();

stud1 = new UndergraduateStudent();

stud1 = new GraduateStudent();

Polymorpic Reference

Page 5: Inheritance & Polymorphism - 2

When a method is invoked using the superclass variable, it is the class of the object (not of the variable type) that determines which method is run.

Student stud1 = new Student();

stud1.computeCourseGrade();

stud1 = new UndergraduateStudent();

stud1.computeCourseGrade();

stud1 = new GraduateStudent();

stud1.computeCourseGrade();

Polymorphic Behaviour

Page 6: Inheritance & Polymorphism - 2

The superclass type variable can only be used to invoke methods in subclass that also exist in the superclass (overridden by subclass). New methods in subclass is not visible to the superclass variable.

Eg. If UndergraduateStudent has a method printUG():

Student stud1 = stud1 = new UndergraduateStudent();

stud1.printUG(); //======== error!!

Polymorphic Behaviour

Page 7: Inheritance & Polymorphism - 2

Creating the roster Array

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 8: Inheritance & Polymorphism - 2

State of the roster Array

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

Page 9: Inheritance & Polymorphism - 2

Sample Polymorphic Message

To compute the course grade using the roster array, we execute

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.

for (int i = 0; i < numberOfStudents; i++) {

roster[i].computeCourseGrade();

}

Page 10: Inheritance & Polymorphism - 2

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 11: Inheritance & Polymorphism - 2

Abstract class

a class that cannot be instantiated but that can be the parent of other classes.

objects can ONLY be created from subclass that inherits from the abstract super (parent) class

the subclass is forced to implement the abstract method inherited from the super class through the overriding process

Page 12: Inheritance & Polymorphism - 2

Java Abstract classes

An abstract class is a class that is declared with the reserved word abstract in its heading.

abstract class ClassName { . . . . . // definitions of methods and variables

}

Page 13: Inheritance & Polymorphism - 2

Abstract classes rules

An abstract class can contain instance variables, constructors, the finalizer, and nonabstract methods

An abstract class can contain abstract method(s).

If a class contains an abstract method, then the class must be declared abstract.

We cannot instantiate an object from abstract class. We can only declare a reference variable of an abstract class type.

We can instantiate an object of a subsclass of an abstract class, but only if the class gives the definitions of all the abstract methods of the superclass.

Page 14: Inheritance & Polymorphism - 2

An abstract method is a method that has only the header without body.

The header of an abstract method must contain the reserved word abstract and ends with semicolon(;).

Syntax: <AccessSpecifier> abstract ReturnType MethodName(ParameterList);

E.g.

public abstract void print(); public abstract String larger(int value); void abstract insert(Object item);

Abstract method

Page 15: Inheritance & Polymorphism - 2

Example of an abstract class & method

public abstract class Animal

{

protected String type;

public void setType(String t)

{ type = t;

}

public abstract void sound();

}

Page 16: Inheritance & Polymorphism - 2

Abstract method rules

Abstract method declaration must be ended with semicolon (;)

Abstract method cannot be private type because a private members cannot be accessed.

Constructor and static method cannot be used as abstract method.

Must be overridden by non-abstract subclass

Page 17: Inheritance & Polymorphism - 2

Abstract class declaration

abstract class Card { String recipient; // name of who gets the card public abstract void greeting(); //abstract greeting() method

}

Page 18: Inheritance & Polymorphism - 2

Abstract Class Card and its Subclasses

abstract Card

abstract greeting( )

AidulFitriCard

greeting( )

BirthdayCard

greeting( )

String recipient

int ageint syawalYear

Page 19: Inheritance & Polymorphism - 2

Abstract method MUST be overridden by subclass

public abstract class Card{ String recipient; public abstract String greeting();}

public class AidulFitriCard extends Card{ int syawalYear; public String greeting() {

………. }}

public class BirthdayCard extends Card{ int age; public String greeting() {

……….. }}

Page 20: Inheritance & Polymorphism - 2

AidulFitriCard Class

public class AidulFitriCard extends Card{ int syawalYear;

public AidulFitriCard(String who, int year) { recipient = who; syawalYear = year; }

public String greeting() { System.out.println(“To “ + recipient); System.out.println(“Selamat Hari Raya Aidul Fitri”); System.out.println(“1 Syawal “ + syawalYear); }}

Page 21: Inheritance & Polymorphism - 2

BirthdayCard Class

public class BirthdayCard extends ________{ int age;

public _____________(String who, int year) { recipient = who; age = year; }

public String greeting() {

System.out.println(“Happy birthday to “+ _______); System.out.println(“You are now “ +age+ “ years old.”);

}}

Page 22: Inheritance & Polymorphism - 2

CardTester Program

public class CardTester { public static void main ( String[] args ) { String name; Scanner input = new Scanner(System.in); System.out.print(“Your name please>"); name = input.nextLine(); Card myCard = new AidulFitri( me, 1429 ); myCard.greeting(); myCard = new BirthdayCard( me, 35 ); myCard.greeting(); }}

- Demonstrate abstract class and polymorphism