SlideShare a Scribd company logo
1 of 22
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
CatRabbit
myPet = 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

More Related Content

What's hot

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 

What's hot (20)

‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 
Object Oriented Programming_Lecture 2
Object Oriented Programming_Lecture 2Object Oriented Programming_Lecture 2
Object Oriented Programming_Lecture 2
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثة
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
 
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Abstract method
Abstract methodAbstract method
Abstract method
 
Inheritance
InheritanceInheritance
Inheritance
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 
Oop in kotlin
Oop in kotlinOop in kotlin
Oop in kotlin
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
 
Object Oriented Principles
Object Oriented PrinciplesObject Oriented Principles
Object Oriented Principles
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
OOP Concepets and UML Class Diagrams
OOP Concepets and UML Class DiagramsOOP Concepets and UML Class Diagrams
OOP Concepets and UML Class Diagrams
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 

Similar to Inheritance & Polymorphism - 2

Chapter 8.3
Chapter 8.3Chapter 8.3
Chapter 8.3
sotlsoc
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
Terry Yoast
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 
Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
Vince Vo
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdf
BapanKar2
 

Similar to Inheritance & Polymorphism - 2 (20)

Chapter 8.3
Chapter 8.3Chapter 8.3
Chapter 8.3
 
Chap11
Chap11Chap11
Chap11
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Chap3 inheritance
Chap3 inheritanceChap3 inheritance
Chap3 inheritance
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Java02
Java02Java02
Java02
 
Classes2
Classes2Classes2
Classes2
 
Abstract classes
Abstract classesAbstract classes
Abstract classes
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdf
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
.NET F# Abstract class interface
.NET F# Abstract class interface.NET F# Abstract class interface
.NET F# Abstract class interface
 
Java basics
Java basicsJava basics
Java basics
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 

More from PRN USM

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
PRN USM
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
PRN USM
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
PRN USM
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
PRN USM
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
PRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
PRN USM
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree Homes
PRN USM
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
PRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
PRN USM
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
PRN USM
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco Control
PRN USM
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From Mhpb
PRN USM
 

More from PRN USM (19)

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Array
ArrayArray
Array
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree Homes
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco Control
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From Mhpb
 

Recently uploaded

The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
heathfieldcps1
 
IATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdffIATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdff
17thcssbs2
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
ashishpaul799
 

Recently uploaded (20)

Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
 Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
 
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
 
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
 
....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).
 
How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
REPRODUCTIVE TOXICITY STUDIE OF MALE AND FEMALEpptx
REPRODUCTIVE TOXICITY  STUDIE OF MALE AND FEMALEpptxREPRODUCTIVE TOXICITY  STUDIE OF MALE AND FEMALEpptx
REPRODUCTIVE TOXICITY STUDIE OF MALE AND FEMALEpptx
 
factors influencing drug absorption-final-2.pptx
factors influencing drug absorption-final-2.pptxfactors influencing drug absorption-final-2.pptx
factors influencing drug absorption-final-2.pptx
 
MichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdfMichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdf
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
philosophy and it's principles based on the life
philosophy and it's principles based on the lifephilosophy and it's principles based on the life
philosophy and it's principles based on the life
 
An Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptxAn Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptx
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 
IATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdffIATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdff
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
 

Inheritance & Polymorphism - 2

  • 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.
  • 3. 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 CatRabbit myPet = new Rabbit();
  • 4.  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
  • 5.  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
  • 6.  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
  • 7. 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(); . . .
  • 8. State of the roster Array  The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes.
  • 9. 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(); }
  • 10. 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++; } }
  • 11. 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
  • 12. 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 }
  • 13. 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.
  • 14.  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
  • 15. Example of an abstract class & method public abstract class Animal { protected String type; public void setType(String t) { type = t; } public abstract void sound(); }
  • 16. 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
  • 17. Abstract class declaration abstract class Card { String recipient; // name of who gets the card public abstract void greeting(); //abstract greeting() method }
  • 18. Abstract Class Card and its Subclasses abstract Card abstract greeting( ) AidulFitriCard greeting( ) BirthdayCard greeting( ) String recipient int ageint syawalYear
  • 19. 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() { ……….. } }
  • 20. 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); } }
  • 21. 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.”); } }
  • 22. 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