View
228
Download
12
Category
Tags:
Preview:
DESCRIPTION
Chapter 2
Citation preview
Polymorphism&
Abstract Class
Polymorphism&
Abstract Class
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.
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();
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
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
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
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();
. . .
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
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();
}
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 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
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
}
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.
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
Example of an abstract class & method
public abstract class Animal
{
protected String type;
public void setType(String t)
{ type = t;
}
public abstract void sound();
}
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
Abstract class declaration
abstract class Card { String recipient; // name of who gets the card public abstract void greeting(); //abstract greeting() method
}
Abstract Class Card and its Subclasses
abstract Card
abstract greeting( )
AidulFitriCard
greeting( )
BirthdayCard
greeting( )
String recipient
int ageint syawalYear
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() {
……….. }}
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); }}
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.”);
}}
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
Recommended