SlideShare a Scribd company logo
CHAPTER 8 INHERITANCE AND
POLYMORPHISM
Oum Saokosal, Chief of Computer Science
National Polytechnic Institute of Cambodia
Tel: (855)-12-252-752
E-mail: oum_saokosal@yahoo.com
1
CHAPTER 8
Polymorphism
2
Polymorphism
1. What is polymorphism?
2. Why polymorphism?
3. Specific uses of polymorphism
4. Notes
5. Remember
6. Casting
7. instanceof Operations
8. Remember
3
What is Polymorphism? (1)
• OOP has 3 features:
1. Class encapsulation
2. Inheritance
3. Polymorphism
• Polymorphism is a mechanism to allow a single variable
to refer to objects from different classes.
4
What is Polymorphism? Example (2)
• Assume we have GraduateStudent which inherits from
Student. Here is an example.
public class Student{
public String getClassName(){
return "Student Class";
}
}
5
Student
+getClassName():String
UndergraduateStudent
+getClassName():String
GraduateStudent
+getClassName():String
What is Polymorphism? Example (3)
//Continue ...
public class GraduateStudent extends Student{
@Override public String getClassName(){
return "GraduateStudent Class";
}
}
public class UndergraduateStudent extends Student{
@Override public String getClassName(){
return “UndergraduateStudent Class";
}
}
6
What is Polymorphism? Test 1 (4)
//Test1 1 – Polymorphism
public class TestPoly1{
public static void main(String[] args){
Student s = new UndergraduateStudent();
System.out.println(s.getClassName());
}
}
Q. What is output?
A. UnderGraduateStudent Class
7
That’s polymorphism
What is Polymorphism? Test 2 (5)
//Example 2 – Without Polymorphism
public class TestNoPoly2 {
public static void main(String[] args){
GraduateStudent gs = new GraduateStudent();
displayUnder(gs);
displayGraduate(new UndergraduateStudent());
}
static void displayUnder(GraduateStudent gs){
System.out.println(gs.getClassName());
}
static void displayGraduate(UndergraduateStudent us){
System.out.println(us.getClassName());
}
}
8
What is Polymorphism? Test 2 (6)
//Example 2 – With Polymorphism
public class TestPoly2 {
public static void main(String[] args){
display(new GraduateStudent());
display(new UndergraduateStudent());
}
//Polymorphic method
public static void display(Student stu){
System.out.println(stu.getClassName());
}
}
9
Why Polymorphism? (1)
• Why Polymorphism?
1. To choose which method from which class is called at
runtime dynamically.
2. A variable of a parent type can refer to any child and
grand child of the parent.
Student stu = new GraduateStudent();
stu.getClassName();
10
Student
getClassName():String
UndergraduateStudent
getClassName():String
GraduateStudent
getClassName():String
Parent/Superclass Children/Subclass
Specific Uses of Polymorphism
Methods (1)
Methods
• If we don’t use polymorphism, you have to make a new
method for every different parameter data type. Look at
slide 8.
• But with polymorphism, you make only one method for
every parameter which has the same parent. Look at
slide 9.
11
Specific Uses of Polymorphism
Array (2)
Array: In Java, every element in an array has the same
type, doesn’t it? E.g.
double[] scores = new double[10];
scores[0] = 1.4;
scores[1] = “Hi”; //Compile Error
Circle[] circles = new Circle[5];
circles[0] = new Circle(5);
circles[1] = new Circle(20);
circles[2] = new Student();//Compile Error
12
Specific Uses of Polymorphism
Array (3)
Q. If I do want to store different types of objects in one
array, how can I do it?
A. Use polymorphism.
If the objects are inherited from the same parent, we
can store them in the same array.
Example:
Student[] students = new Student[3];
students[0] = new Student();
students[1] = new GraduateStudent();
students[2] = new UndergraduateStudent();
13
Specific usages of Polymorphism
Array (4)
public class TestPoly3 {
public static void main(String[] args){
Student[] s = new Student[3];
s[0] = new Student();
s[1] = new GraduateStudent();
s[2] = new UndergraduateStudent();
display(s); //Polymorphism
}
public static void display(Student[] s){
for(int i = 0; i<s.length; i++){
System.out.println(s[i].getClassName());
}
}
}
14
Note #1 (1)
• Look at the codes again.
public class Student{
public String getClassName(){
return "Student Class";
}
}
public class GraduateStudent extends Student{
@Override public String getClassName(){
return "GraduateStudent Class";
}
}
public class UndergraduateStudent extends Student{
@Override public String getClassName(){
return “UndergraduateStudent Class";
}
}
15
GraduateStudent and
UndergraduateStudent
override getClassName()
method!
Note #1 (2)
• Please note that the two subclasses of Student override
getClassName().
Then, we can use polymorphism to refer to getClassName() in
the sub class.
public class TestPoly1{
public static void main(String[] args){
Student s;
s = new GraduateStudent();
System.out.println(s.getClassName());
s = new UndergraduateStudent();
System.out.println(s.getClassName());
}
}
16
Note #2 (1)
• But now in a subclass GraduateStudent, we add a
new method, say getDegree().
public class GraduateStudent extends Student{
public String getClassName(){
return "GraduateStudent Class";
}
public String getDegree(){
return "Msc in Computer Science";
}
}
17
Note #2 (2)
• And then we want to use polymorphism to call
getDegree() in the subclass,
public class TestPoly1{
public static void main(String[] args){
Student s = new GraduateStudent();
System.out.println(s.getDegree());
}
}
It will show a compile error because Student class
doesn’t have getDegree().
18
Note #3 (1)
• What about if we want add a method, say getID() to
the parent, Student.
public class Student{
public String getClassName(){
return "Student Class";
}
public String getID(){
return “NPIC001";
}
}
19
Note #3 (2)
• Then we want to call getID().
public class TestPoly1{
public static void main(String[] args){
Student s = new GraduateStudent();
System.out.println(s.getID());
}
}
Q. Is it a compile error?
A. No. As long as getID() is in Student, we can call
it without any question.
20
The bottom line (1)
1. As long as subclasses inherit from the same parent, you
can declare a variable as the parent type and then refer
to any subclasses.
Student stu; //stu is parent type
//stu refers to subclasses
stu = new UndergraduateStudent();
stu = new GraduateStudent();
21
Student
getClassName():String
UndergraduateStudent
getClassName():String
GraduateStudent
getClassName():String
The bottom line (2)
2. When you call a method which exists both in a parent
and subclass, then it will dynamically refer to the
method in the subclass. (This is the main reason to use
Polymorphism) See slide 7.
3. You cannot call methods that are NOT existed in
parent. If you try it, you will get compile error.
See slide 18.
4. However, you can call every method in the superclass.
See slide 19 & 20.
22
Remember (1)
• Polymorphism is a mechanism to enable us to choose a
method at runtime dynamically.
• Polymorphism always needs Inheritance.
• Polymorphism always needs Overridden Methods.
• There is no keyword to indicate Polymorphism.
• You can recognise it whenever you see a class type that is
different from its constructor. E.g.
Student s = new GraduateStudent();
• You can also recognise it, when a class type is Object
class. E.g.
private void aMethod(Object ob){...}
23
Remember (2)
• Polymorphism is not as vital as inheritance. That is,
without polymorphism, you still CAN make a Java
program; however without inheritance, especially when
using Java library code, you CANNOT achieve very much.
24
Casting Objects (1)
• What is Casting?
Casting is a technique to convert a variable from one
primitive type to another one. E.g.:
double d1 = 2.5;
double d2 = 12;
int i1 = 23;
int i2 = 22.5; // Compile Error
• How to solve this error?
int i2 = (int) 22.5; // i2 = 22
//Casting from double 22.5 to integer.
25
Casting Objects (2)
• To understand casting, let’s meet a group of animals
studying polymorphism.
26
SR: Smart Rabbit
CB: Curious Ball
CB is a curious student who always asks questions
whereas SR is a smart student. She can help to answer
CB’s questions.
Casting Objects (3)
CB: Hey Smart Rabbit! Can I ask you some questions?
SR: Yes, Of course. What can I do for ya?
CB: I have 2 classes, Grape inherits from Fruit.
27
Casting Objects (4)
SR: So what?
CB: Grape has four methods. And Fruit has only two
methods. Then I want to use polymorphism like this:
Fruit f = new Grape();
So which methods can I call from f?
f._ _ _ ?
SR: Then you can call only those methods from Fruit
class like isEatable() and getColor(), and, of
course, other 9 methods from Object class.
28
Casting Objects (5)
CB: You know, usually when I define a variable with a
parent type and refer to a constructor from the same
class, I can call every method from it.
Grape g = new Grape();
g.getTaste(); // OK
g.getVitamin(); //OK
SR: Yeh, and what is your problem?
CB: But now when I use polymorphism, it seems to me
that I couldn’t do what I used to do.
Fruit fruit = new Grape();
fruit.getTaste(); // Compile Error
fruit.getVitamin(); // Compile Error
29
Casting Objects (6)
CB: So do you have any solution, Rabbit?
SR: Why not? You can use “casting” to cast from
Fruit to another Grape variable.
CB: Can you show me?
SR: Sure! Here it is:
Fruit fruit = new Grape();
Grape grape = (Grape) fruit; // Casting
grape.getTaste(); //OK
grape.getVitamin(); //OK
30
Casting Objects (6)
CB: Yeh... but you still create a variable that has Grape
as its parent type. It doesn’t make sense to me?
SR: Why not?
CB: You know, it is much better if I just create a
variable which has Grape as its type and refer to its
constructor since the beginning like this:
Grape g = new Grape();
g.getTaste(); // OK
g.getVitamin(); //OK
31
Casting Objects (7)
SR: Well, but do you remember polymorphic method?
CB: Yes.
SR: So can I tell me some about it?
CB: polymorphic method is just like other methods but
the type of parameters is always a superclass. For
example:
public static void display(Object o){
JOptionPane.showMessageDialog(null, o);
}
SR: Yehh! You are good!
32
Casting Objects (8)
CB: Thank you. But how polymorphic method works with casting?
SR: OK! I’ll show you the differences when not using casting and when
using casting.
public class TestNoCasting {
public static void main(String[] args){
showTaste(new Grape());
}
public static void showTaste(Fruit fruit){
JOptionPane.showMessageDialog(null,
fruit.getTaste());
} //Error because Fruit has not getTaste()
}
33
Casting Objects (9)
SR: Here is codes when using casting.
public class TestCastingObject {
public static void main(String[] args){
showTaste(new Grape());
}
public static void showTaste(Fruit fruit){
Grape grape = (Grape) fruit;
JOptionPane.showMessageDialog(null,
grape.getTaste()); //OK
}
}
34
Casting Objects (10)
CB: Wow! Now I got. Casting can help polymorphism
more powerful. Both Java and you are very smart.
SR: Not yet dude!
CB: What else?
SR: What about if I add another class, say Apple
inherits also from Fruit? Let’s see it on the next
slide.
35
Casting Objects (11)
36
Casting Objects (11)
SR: Then I pass in Apple object to showTaste() method.
public class TestCastingObject {
public static void main(String[] args){
showTaste(new Apple());
}
public static void showTaste(Fruit fruit){
Grape grape = (Grape) fruit;
JOptionPane.showMessageDialog(null,
grape.getTaste());
}
}//Runtime Error: casting wrong class
37
instanceof Operation (1)
CB: Wo.. ho.. ho. I didn’t realize it.
SR: Don’t worry! Remember Java is number one in the
world.
CB: So what is your solution?
SR: We can use instanceof to test whether it is
correct object or not before we cast it.
CB: Can you show how?
SR: OK, Let’s go to the next slide.
38
instanceof Operation (2)
public static void main(String[] args) {
showTaste(new Apple());
}
public static void showTaste(Fruit fruit) {
if (fruit instanceof Grape) {
Grape grape = (Grape) fruit;
System.out.print(grape.getTaste());
} else if(fruit instanceof Apple) {
Apple apple = (Apple) fruit;
System.out.print(apple.getTaste());
}
}
39
instanceof Operation (3)
40
CB: OK. It seems to me that I know them all,
but I want to ask you, Smart Rabbit,
whether the 3rd year students in NPIC who
are watching us understand it or not.
SR: This is a hard question. I’m
not sure either. You’ve better
ask them by yourself.
Remember (1)
• Casting is a technique to convert a variable from one
class type to another one within an inheritance hierarchy.
That is, if we cast a class to another class in different root,
you will get run-time error. E.g:
Fruit fruit = new Grape();
Grape grape = (Grape) fruit;// OK
Apple apple = (Apple) fruit;//Runtime Error
41
Remember (2)
• A keyword instanceof is an operation to check whether a
class that we want to cast is in the correct hierarchy or
not.
• E.g.:
Fruit fruit = new Grape();
if(fruit instanceof Grape){
Grape grape = (Grape) fruit;
} else if(fruit instanceof Apple){
Apple apple = (Apple) fruit;
}
fruit.getColor();
fruit.getTaste();
42

More Related Content

What's hot (20)

Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
Ddl &amp; dml commands
Ddl &amp; dml commandsDdl &amp; dml commands
Ddl &amp; dml commands
AnjaliJain167
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Lovely Professional University
 
JAVA - ENCAPSULAMENTO
JAVA - ENCAPSULAMENTOJAVA - ENCAPSULAMENTO
JAVA - ENCAPSULAMENTO
André Victor
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Hitesh Kumar
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
Hitesh-Java
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Arif Ansari
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
JavaTportal
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
Sohanur63
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
Lovely Professional University
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
Knoldus Inc.
 
C# Overriding
C# OverridingC# Overriding
C# Overriding
Prem Kumar Badri
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
Anjan Kumar Bollam
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
Jason Straughan
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
PravinYalameli
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
Nilesh Dalvi
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
Ddl &amp; dml commands
Ddl &amp; dml commandsDdl &amp; dml commands
Ddl &amp; dml commands
AnjaliJain167
 
JAVA - ENCAPSULAMENTO
JAVA - ENCAPSULAMENTOJAVA - ENCAPSULAMENTO
JAVA - ENCAPSULAMENTO
André Victor
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Hitesh Kumar
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
Hitesh-Java
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
JavaTportal
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
Sohanur63
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
Knoldus Inc.
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
PravinYalameli
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
Nilesh Dalvi
 

Viewers also liked (20)

Objected-Oriented Programming with Java
Objected-Oriented Programming with JavaObjected-Oriented Programming with Java
Objected-Oriented Programming with Java
Oum Saokosal
 
11.1 Android with HTML
11.1 Android with HTML11.1 Android with HTML
11.1 Android with HTML
Oum Saokosal
 
10.3 Android Video
10.3 Android Video10.3 Android Video
10.3 Android Video
Oum Saokosal
 
Java Programming - Introduction to Abstract Class
Java Programming - Introduction to Abstract ClassJava Programming - Introduction to Abstract Class
Java Programming - Introduction to Abstract Class
Oum Saokosal
 
Database Concept - ERD Mapping to MS Access
Database Concept - ERD Mapping to MS AccessDatabase Concept - ERD Mapping to MS Access
Database Concept - ERD Mapping to MS Access
Oum Saokosal
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)
Oum Saokosal
 
Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)
Oum Saokosal
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
Oum Saokosal
 
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NFDatabase Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Oum Saokosal
 
Android - Introduction
Android - IntroductionAndroid - Introduction
Android - Introduction
Oum Saokosal
 
10.1. Android Audio
10.1. Android Audio10.1. Android Audio
10.1. Android Audio
Oum Saokosal
 
07.4. Android Basic Simple Browser (WebView)
07.4. Android Basic Simple Browser (WebView)07.4. Android Basic Simple Browser (WebView)
07.4. Android Basic Simple Browser (WebView)
Oum Saokosal
 
04. Review OOP with Java
04. Review OOP with Java04. Review OOP with Java
04. Review OOP with Java
Oum Saokosal
 
07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete
Oum Saokosal
 
06. Android Basic Widget and Container
06. Android Basic Widget and Container06. Android Basic Widget and Container
06. Android Basic Widget and Container
Oum Saokosal
 
08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)
Oum Saokosal
 
Using intents in android
Using intents in androidUsing intents in android
Using intents in android
Oum Saokosal
 
10.2 Android Audio with SD Card
10.2 Android Audio with SD Card10.2 Android Audio with SD Card
10.2 Android Audio with SD Card
Oum Saokosal
 
07.1. Android Even Handling
07.1. Android Even Handling07.1. Android Even Handling
07.1. Android Even Handling
Oum Saokosal
 
12. Android Basic Google Map
12. Android Basic Google Map12. Android Basic Google Map
12. Android Basic Google Map
Oum Saokosal
 
Objected-Oriented Programming with Java
Objected-Oriented Programming with JavaObjected-Oriented Programming with Java
Objected-Oriented Programming with Java
Oum Saokosal
 
11.1 Android with HTML
11.1 Android with HTML11.1 Android with HTML
11.1 Android with HTML
Oum Saokosal
 
10.3 Android Video
10.3 Android Video10.3 Android Video
10.3 Android Video
Oum Saokosal
 
Java Programming - Introduction to Abstract Class
Java Programming - Introduction to Abstract ClassJava Programming - Introduction to Abstract Class
Java Programming - Introduction to Abstract Class
Oum Saokosal
 
Database Concept - ERD Mapping to MS Access
Database Concept - ERD Mapping to MS AccessDatabase Concept - ERD Mapping to MS Access
Database Concept - ERD Mapping to MS Access
Oum Saokosal
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)
Oum Saokosal
 
Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)
Oum Saokosal
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
Oum Saokosal
 
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NFDatabase Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Database Normalization 1NF, 2NF, 3NF, BCNF, 4NF, 5NF
Oum Saokosal
 
Android - Introduction
Android - IntroductionAndroid - Introduction
Android - Introduction
Oum Saokosal
 
10.1. Android Audio
10.1. Android Audio10.1. Android Audio
10.1. Android Audio
Oum Saokosal
 
07.4. Android Basic Simple Browser (WebView)
07.4. Android Basic Simple Browser (WebView)07.4. Android Basic Simple Browser (WebView)
07.4. Android Basic Simple Browser (WebView)
Oum Saokosal
 
04. Review OOP with Java
04. Review OOP with Java04. Review OOP with Java
04. Review OOP with Java
Oum Saokosal
 
07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete
Oum Saokosal
 
06. Android Basic Widget and Container
06. Android Basic Widget and Container06. Android Basic Widget and Container
06. Android Basic Widget and Container
Oum Saokosal
 
08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)
Oum Saokosal
 
Using intents in android
Using intents in androidUsing intents in android
Using intents in android
Oum Saokosal
 
10.2 Android Audio with SD Card
10.2 Android Audio with SD Card10.2 Android Audio with SD Card
10.2 Android Audio with SD Card
Oum Saokosal
 
07.1. Android Even Handling
07.1. Android Even Handling07.1. Android Even Handling
07.1. Android Even Handling
Oum Saokosal
 
12. Android Basic Google Map
12. Android Basic Google Map12. Android Basic Google Map
12. Android Basic Google Map
Oum Saokosal
 
Ad

Similar to Java Programming - Polymorphism (20)

Chapter 8 Polymorphism
Chapter 8 PolymorphismChapter 8 Polymorphism
Chapter 8 Polymorphism
OUM SAOKOSAL
 
Polymorphism in OPP, JAVA, Method overload.pptx
Polymorphism in OPP, JAVA, Method overload.pptxPolymorphism in OPP, JAVA, Method overload.pptx
Polymorphism in OPP, JAVA, Method overload.pptx
AsifMehmood240435
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
OUM SAOKOSAL
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
ParikhitGhosh1
 
InheritanceAndPolymorphismprein Java.ppt
InheritanceAndPolymorphismprein Java.pptInheritanceAndPolymorphismprein Java.ppt
InheritanceAndPolymorphismprein Java.ppt
gayatridwahane
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
mcollison
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptx
Hailsh
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
Animesh Sarkar
 
Java 2 chapter 10 - basic oop in java
Java 2   chapter 10 - basic oop in javaJava 2   chapter 10 - basic oop in java
Java 2 chapter 10 - basic oop in java
let's go to study
 
2 Object-oriented programghgrtrdwwe.pptx
2 Object-oriented programghgrtrdwwe.pptx2 Object-oriented programghgrtrdwwe.pptx
2 Object-oriented programghgrtrdwwe.pptx
RamaDalabeh
 
Lecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptxLecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptx
ShahinAhmed49
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
Sonu WIZIQ
 
Multiple inheritance
Multiple inheritanceMultiple inheritance
Multiple inheritance
zindadili
 
Object Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;sObject Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;s
vivek p s
 
Polymorphism.pptthis is oops one of the most important feature polymorphism
Polymorphism.pptthis is oops one of the most important feature polymorphismPolymorphism.pptthis is oops one of the most important feature polymorphism
Polymorphism.pptthis is oops one of the most important feature polymorphism
rgvaryan
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
amitarcade
 
Java generics final
Java generics finalJava generics final
Java generics final
Akshay Chaudhari
 
Lecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptxLecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptx
IkaDeviPerwitasari1
 
Chapter 8 Polymorphism
Chapter 8 PolymorphismChapter 8 Polymorphism
Chapter 8 Polymorphism
OUM SAOKOSAL
 
Polymorphism in OPP, JAVA, Method overload.pptx
Polymorphism in OPP, JAVA, Method overload.pptxPolymorphism in OPP, JAVA, Method overload.pptx
Polymorphism in OPP, JAVA, Method overload.pptx
AsifMehmood240435
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
OUM SAOKOSAL
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
ParikhitGhosh1
 
InheritanceAndPolymorphismprein Java.ppt
InheritanceAndPolymorphismprein Java.pptInheritanceAndPolymorphismprein Java.ppt
InheritanceAndPolymorphismprein Java.ppt
gayatridwahane
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
mcollison
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptx
Hailsh
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
Animesh Sarkar
 
Java 2 chapter 10 - basic oop in java
Java 2   chapter 10 - basic oop in javaJava 2   chapter 10 - basic oop in java
Java 2 chapter 10 - basic oop in java
let's go to study
 
2 Object-oriented programghgrtrdwwe.pptx
2 Object-oriented programghgrtrdwwe.pptx2 Object-oriented programghgrtrdwwe.pptx
2 Object-oriented programghgrtrdwwe.pptx
RamaDalabeh
 
Lecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptxLecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptx
ShahinAhmed49
 
Multiple inheritance
Multiple inheritanceMultiple inheritance
Multiple inheritance
zindadili
 
Object Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;sObject Oriented Principle&rsquo;s
Object Oriented Principle&rsquo;s
vivek p s
 
Polymorphism.pptthis is oops one of the most important feature polymorphism
Polymorphism.pptthis is oops one of the most important feature polymorphismPolymorphism.pptthis is oops one of the most important feature polymorphism
Polymorphism.pptthis is oops one of the most important feature polymorphism
rgvaryan
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
amitarcade
 
Lecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptxLecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptx
IkaDeviPerwitasari1
 
Ad

Recently uploaded (20)

LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 

Java Programming - Polymorphism

  • 1. CHAPTER 8 INHERITANCE AND POLYMORPHISM Oum Saokosal, Chief of Computer Science National Polytechnic Institute of Cambodia Tel: (855)-12-252-752 E-mail: [email protected] 1
  • 3. Polymorphism 1. What is polymorphism? 2. Why polymorphism? 3. Specific uses of polymorphism 4. Notes 5. Remember 6. Casting 7. instanceof Operations 8. Remember 3
  • 4. What is Polymorphism? (1) • OOP has 3 features: 1. Class encapsulation 2. Inheritance 3. Polymorphism • Polymorphism is a mechanism to allow a single variable to refer to objects from different classes. 4
  • 5. What is Polymorphism? Example (2) • Assume we have GraduateStudent which inherits from Student. Here is an example. public class Student{ public String getClassName(){ return "Student Class"; } } 5 Student +getClassName():String UndergraduateStudent +getClassName():String GraduateStudent +getClassName():String
  • 6. What is Polymorphism? Example (3) //Continue ... public class GraduateStudent extends Student{ @Override public String getClassName(){ return "GraduateStudent Class"; } } public class UndergraduateStudent extends Student{ @Override public String getClassName(){ return “UndergraduateStudent Class"; } } 6
  • 7. What is Polymorphism? Test 1 (4) //Test1 1 – Polymorphism public class TestPoly1{ public static void main(String[] args){ Student s = new UndergraduateStudent(); System.out.println(s.getClassName()); } } Q. What is output? A. UnderGraduateStudent Class 7 That’s polymorphism
  • 8. What is Polymorphism? Test 2 (5) //Example 2 – Without Polymorphism public class TestNoPoly2 { public static void main(String[] args){ GraduateStudent gs = new GraduateStudent(); displayUnder(gs); displayGraduate(new UndergraduateStudent()); } static void displayUnder(GraduateStudent gs){ System.out.println(gs.getClassName()); } static void displayGraduate(UndergraduateStudent us){ System.out.println(us.getClassName()); } } 8
  • 9. What is Polymorphism? Test 2 (6) //Example 2 – With Polymorphism public class TestPoly2 { public static void main(String[] args){ display(new GraduateStudent()); display(new UndergraduateStudent()); } //Polymorphic method public static void display(Student stu){ System.out.println(stu.getClassName()); } } 9
  • 10. Why Polymorphism? (1) • Why Polymorphism? 1. To choose which method from which class is called at runtime dynamically. 2. A variable of a parent type can refer to any child and grand child of the parent. Student stu = new GraduateStudent(); stu.getClassName(); 10 Student getClassName():String UndergraduateStudent getClassName():String GraduateStudent getClassName():String Parent/Superclass Children/Subclass
  • 11. Specific Uses of Polymorphism Methods (1) Methods • If we don’t use polymorphism, you have to make a new method for every different parameter data type. Look at slide 8. • But with polymorphism, you make only one method for every parameter which has the same parent. Look at slide 9. 11
  • 12. Specific Uses of Polymorphism Array (2) Array: In Java, every element in an array has the same type, doesn’t it? E.g. double[] scores = new double[10]; scores[0] = 1.4; scores[1] = “Hi”; //Compile Error Circle[] circles = new Circle[5]; circles[0] = new Circle(5); circles[1] = new Circle(20); circles[2] = new Student();//Compile Error 12
  • 13. Specific Uses of Polymorphism Array (3) Q. If I do want to store different types of objects in one array, how can I do it? A. Use polymorphism. If the objects are inherited from the same parent, we can store them in the same array. Example: Student[] students = new Student[3]; students[0] = new Student(); students[1] = new GraduateStudent(); students[2] = new UndergraduateStudent(); 13
  • 14. Specific usages of Polymorphism Array (4) public class TestPoly3 { public static void main(String[] args){ Student[] s = new Student[3]; s[0] = new Student(); s[1] = new GraduateStudent(); s[2] = new UndergraduateStudent(); display(s); //Polymorphism } public static void display(Student[] s){ for(int i = 0; i<s.length; i++){ System.out.println(s[i].getClassName()); } } } 14
  • 15. Note #1 (1) • Look at the codes again. public class Student{ public String getClassName(){ return "Student Class"; } } public class GraduateStudent extends Student{ @Override public String getClassName(){ return "GraduateStudent Class"; } } public class UndergraduateStudent extends Student{ @Override public String getClassName(){ return “UndergraduateStudent Class"; } } 15 GraduateStudent and UndergraduateStudent override getClassName() method!
  • 16. Note #1 (2) • Please note that the two subclasses of Student override getClassName(). Then, we can use polymorphism to refer to getClassName() in the sub class. public class TestPoly1{ public static void main(String[] args){ Student s; s = new GraduateStudent(); System.out.println(s.getClassName()); s = new UndergraduateStudent(); System.out.println(s.getClassName()); } } 16
  • 17. Note #2 (1) • But now in a subclass GraduateStudent, we add a new method, say getDegree(). public class GraduateStudent extends Student{ public String getClassName(){ return "GraduateStudent Class"; } public String getDegree(){ return "Msc in Computer Science"; } } 17
  • 18. Note #2 (2) • And then we want to use polymorphism to call getDegree() in the subclass, public class TestPoly1{ public static void main(String[] args){ Student s = new GraduateStudent(); System.out.println(s.getDegree()); } } It will show a compile error because Student class doesn’t have getDegree(). 18
  • 19. Note #3 (1) • What about if we want add a method, say getID() to the parent, Student. public class Student{ public String getClassName(){ return "Student Class"; } public String getID(){ return “NPIC001"; } } 19
  • 20. Note #3 (2) • Then we want to call getID(). public class TestPoly1{ public static void main(String[] args){ Student s = new GraduateStudent(); System.out.println(s.getID()); } } Q. Is it a compile error? A. No. As long as getID() is in Student, we can call it without any question. 20
  • 21. The bottom line (1) 1. As long as subclasses inherit from the same parent, you can declare a variable as the parent type and then refer to any subclasses. Student stu; //stu is parent type //stu refers to subclasses stu = new UndergraduateStudent(); stu = new GraduateStudent(); 21 Student getClassName():String UndergraduateStudent getClassName():String GraduateStudent getClassName():String
  • 22. The bottom line (2) 2. When you call a method which exists both in a parent and subclass, then it will dynamically refer to the method in the subclass. (This is the main reason to use Polymorphism) See slide 7. 3. You cannot call methods that are NOT existed in parent. If you try it, you will get compile error. See slide 18. 4. However, you can call every method in the superclass. See slide 19 & 20. 22
  • 23. Remember (1) • Polymorphism is a mechanism to enable us to choose a method at runtime dynamically. • Polymorphism always needs Inheritance. • Polymorphism always needs Overridden Methods. • There is no keyword to indicate Polymorphism. • You can recognise it whenever you see a class type that is different from its constructor. E.g. Student s = new GraduateStudent(); • You can also recognise it, when a class type is Object class. E.g. private void aMethod(Object ob){...} 23
  • 24. Remember (2) • Polymorphism is not as vital as inheritance. That is, without polymorphism, you still CAN make a Java program; however without inheritance, especially when using Java library code, you CANNOT achieve very much. 24
  • 25. Casting Objects (1) • What is Casting? Casting is a technique to convert a variable from one primitive type to another one. E.g.: double d1 = 2.5; double d2 = 12; int i1 = 23; int i2 = 22.5; // Compile Error • How to solve this error? int i2 = (int) 22.5; // i2 = 22 //Casting from double 22.5 to integer. 25
  • 26. Casting Objects (2) • To understand casting, let’s meet a group of animals studying polymorphism. 26 SR: Smart Rabbit CB: Curious Ball CB is a curious student who always asks questions whereas SR is a smart student. She can help to answer CB’s questions.
  • 27. Casting Objects (3) CB: Hey Smart Rabbit! Can I ask you some questions? SR: Yes, Of course. What can I do for ya? CB: I have 2 classes, Grape inherits from Fruit. 27
  • 28. Casting Objects (4) SR: So what? CB: Grape has four methods. And Fruit has only two methods. Then I want to use polymorphism like this: Fruit f = new Grape(); So which methods can I call from f? f._ _ _ ? SR: Then you can call only those methods from Fruit class like isEatable() and getColor(), and, of course, other 9 methods from Object class. 28
  • 29. Casting Objects (5) CB: You know, usually when I define a variable with a parent type and refer to a constructor from the same class, I can call every method from it. Grape g = new Grape(); g.getTaste(); // OK g.getVitamin(); //OK SR: Yeh, and what is your problem? CB: But now when I use polymorphism, it seems to me that I couldn’t do what I used to do. Fruit fruit = new Grape(); fruit.getTaste(); // Compile Error fruit.getVitamin(); // Compile Error 29
  • 30. Casting Objects (6) CB: So do you have any solution, Rabbit? SR: Why not? You can use “casting” to cast from Fruit to another Grape variable. CB: Can you show me? SR: Sure! Here it is: Fruit fruit = new Grape(); Grape grape = (Grape) fruit; // Casting grape.getTaste(); //OK grape.getVitamin(); //OK 30
  • 31. Casting Objects (6) CB: Yeh... but you still create a variable that has Grape as its parent type. It doesn’t make sense to me? SR: Why not? CB: You know, it is much better if I just create a variable which has Grape as its type and refer to its constructor since the beginning like this: Grape g = new Grape(); g.getTaste(); // OK g.getVitamin(); //OK 31
  • 32. Casting Objects (7) SR: Well, but do you remember polymorphic method? CB: Yes. SR: So can I tell me some about it? CB: polymorphic method is just like other methods but the type of parameters is always a superclass. For example: public static void display(Object o){ JOptionPane.showMessageDialog(null, o); } SR: Yehh! You are good! 32
  • 33. Casting Objects (8) CB: Thank you. But how polymorphic method works with casting? SR: OK! I’ll show you the differences when not using casting and when using casting. public class TestNoCasting { public static void main(String[] args){ showTaste(new Grape()); } public static void showTaste(Fruit fruit){ JOptionPane.showMessageDialog(null, fruit.getTaste()); } //Error because Fruit has not getTaste() } 33
  • 34. Casting Objects (9) SR: Here is codes when using casting. public class TestCastingObject { public static void main(String[] args){ showTaste(new Grape()); } public static void showTaste(Fruit fruit){ Grape grape = (Grape) fruit; JOptionPane.showMessageDialog(null, grape.getTaste()); //OK } } 34
  • 35. Casting Objects (10) CB: Wow! Now I got. Casting can help polymorphism more powerful. Both Java and you are very smart. SR: Not yet dude! CB: What else? SR: What about if I add another class, say Apple inherits also from Fruit? Let’s see it on the next slide. 35
  • 37. Casting Objects (11) SR: Then I pass in Apple object to showTaste() method. public class TestCastingObject { public static void main(String[] args){ showTaste(new Apple()); } public static void showTaste(Fruit fruit){ Grape grape = (Grape) fruit; JOptionPane.showMessageDialog(null, grape.getTaste()); } }//Runtime Error: casting wrong class 37
  • 38. instanceof Operation (1) CB: Wo.. ho.. ho. I didn’t realize it. SR: Don’t worry! Remember Java is number one in the world. CB: So what is your solution? SR: We can use instanceof to test whether it is correct object or not before we cast it. CB: Can you show how? SR: OK, Let’s go to the next slide. 38
  • 39. instanceof Operation (2) public static void main(String[] args) { showTaste(new Apple()); } public static void showTaste(Fruit fruit) { if (fruit instanceof Grape) { Grape grape = (Grape) fruit; System.out.print(grape.getTaste()); } else if(fruit instanceof Apple) { Apple apple = (Apple) fruit; System.out.print(apple.getTaste()); } } 39
  • 40. instanceof Operation (3) 40 CB: OK. It seems to me that I know them all, but I want to ask you, Smart Rabbit, whether the 3rd year students in NPIC who are watching us understand it or not. SR: This is a hard question. I’m not sure either. You’ve better ask them by yourself.
  • 41. Remember (1) • Casting is a technique to convert a variable from one class type to another one within an inheritance hierarchy. That is, if we cast a class to another class in different root, you will get run-time error. E.g: Fruit fruit = new Grape(); Grape grape = (Grape) fruit;// OK Apple apple = (Apple) fruit;//Runtime Error 41
  • 42. Remember (2) • A keyword instanceof is an operation to check whether a class that we want to cast is in the correct hierarchy or not. • E.g.: Fruit fruit = new Grape(); if(fruit instanceof Grape){ Grape grape = (Grape) fruit; } else if(fruit instanceof Apple){ Apple apple = (Apple) fruit; } fruit.getColor(); fruit.getTaste(); 42