SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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

La actualidad más candente (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 a 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 a 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
 

Más de 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
 

Más de 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
 

Último

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Último (20)

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

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