SlideShare a Scribd company logo
1 of 16
POLYMORPHISM &
INTERFACES
Mimi OpkinsCECS 277
Example class hierarchy
Animal
Cat Dog Horse
Polymorphism
 Normally we have this when we create an object:
Dog dog = new Dog();
 Polymorphism allows us to also do this:
Animal pet = new Dog();
 The object reference variable can be a super class of
the actual object type! (Does NOT work the other way
around: Dog is an Animal but Animal is not necessarily
a Dog)
Where Polymorphism is Helpful
 Arrays
 Passing parameters
 Returning values from a method
Polymorphic Array Example
Animal[] myPets = new Animal[5];
myPets[0] = new Cat();
myPets[1] = new Cat();
myPets[3] = new Dog();
for (int i = 0; i < myPets.length; i++) {
myPets.feed();
}
You can put any subclass
of Animal in the Animal
array!
Polymorphic Arguments
public class Vet {
public void giveShot(Animal pet) {
pet.makeNoise();
}
}
public class PetOwner {
Vet vet = new Vet();
Dog dog = new Dog();
Cat cat = new Cat();
vet.giveShot(dog);
vet.giveShot(cat);
}
Abstract Classes
 Sometimes we don’t want to allow an object to
be created of a certain type.
 What exactly would an Animal object be?
 We use the keyword abstract to prevent a
class from ever being instantiated.
abstract public class Animal
Abstract Classes
 Can still use abstract classes as a reference
variable, for the purposes of polymorphism.
 An abstract class has no use until it is
extended!
 A class that is not abstract is called concrete.
Abstract Methods
 An abstract method has no body and is marked
with the keyword abstract.
public abstract void eat();
 If a method is abstract, the class it is contained
in must also be abstract.
 Abstract methods help the programmer to
provide a protocol for a group of subclasses.
 The first concrete class in the inheritance
hierarchy must implement the abstract method
(i.e. override it and provide it a body)
Side Effects of Polymorphism
ArrayList pets = new ArrayList();
Dog dog = new Dog();
pets.add(dog);
int index = pets.indexOf(dog);
Dog dog1 = pets.get(index); // won’t work
Object dog2 = pets.get(index);
dog2.bark(); // won’t work
((Dog)dog2).bark(); // works because of casting
if (dog2 instanceof Dog) { // being careful
((Dog)dog2).bark();
}
Dog dog3 = (Dog) pets.get(index); // works because of casting
if (dog2 instanceof Dog) { // being careful
Dog dog4 = (Dog) dog2;
}
Animal
Canine Feline
Wolf
Dog Cat Tiger Lion
Pet
But remember we said that Java does
not support multiple inheritance. There
is a solution however: interfaces.
Interfaces
 Interface: A collection of constants and
abstract methods that cannot be instantiated.
 A class implements an interface by providing
method implementations for each of the
abstract methods defined in the interface.
public class Dog extends Canine implements Pet
Interfaces
public interface Pet {
public abstract void beFriendly();
public abstract void play();
}
public class Dog extends Canine implements Pet {
public void beFriendly() {
wagTail();
}
public void play() {
chaseBall();
}
. . . all the other Dog methods . . .
}
Explicitly typing in
public and abstract
is not necessary
since they MUST
be public and
abstract
Must implement these
methods since they
are in Pet
Interfaces vs. Subclasses
 Make a subclass only when you want to make
a more specific version of a class.
 Use an interface when you want to define a
role that other classes can play, regardless of
where those classes are in the inheritance
tree.
Polymorphism via Interfaces
 An interface reference variable can be used to
refer to any object of any class that implements
that interface.
 This works the same with superclasses.
Pet myPet = new Dog();
 The same side effects of polymorphism occur
with interfaces as with inheritance.
Comparable Interface
 Defined in the java.lang package
 Only contains one method: compareTo which
takes an object as a parameter and returns an
integer. Returns a negative integer, zero, or a
positive integer as this object is less than, equal
to, or greater than the specified object.
 Provides a common mechanism for comparing
one object to another.
 http://java.sun.com/j2se/1.5.0/docs/api/java/lang/
Comparable.html

More Related Content

Similar to Polymorphism.ppt

On Reflection in OO Programming Languages (v1.5.2, 14/04/14)
On Reflection in OO Programming Languages (v1.5.2, 14/04/14)On Reflection in OO Programming Languages (v1.5.2, 14/04/14)
On Reflection in OO Programming Languages (v1.5.2, 14/04/14)
Yann-Gaël Guéhéneuc
 
Interfaces &amp; Abstract Classes
Interfaces &amp; Abstract ClassesInterfaces &amp; Abstract Classes
Interfaces &amp; Abstract Classes
Bharat17485
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphism
Jussi Pohjolainen
 

Similar to Polymorphism.ppt (20)

10 classes
10 classes10 classes
10 classes
 
Java2
Java2Java2
Java2
 
On Reflection in OO Programming Languages (v1.5.2, 14/04/14)
On Reflection in OO Programming Languages (v1.5.2, 14/04/14)On Reflection in OO Programming Languages (v1.5.2, 14/04/14)
On Reflection in OO Programming Languages (v1.5.2, 14/04/14)
 
Interfaces &amp; Abstract Classes
Interfaces &amp; Abstract ClassesInterfaces &amp; Abstract Classes
Interfaces &amp; Abstract Classes
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphism
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. Polymorphism
 
Kotlin intro
Kotlin introKotlin intro
Kotlin intro
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
 
Design patterns(red)
Design patterns(red)Design patterns(red)
Design patterns(red)
 
Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDD
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Java 8 ​and ​Best Practices
 Java 8 ​and ​Best Practices Java 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Dive into Object Orienter Programming and Design Patterns through java
Dive into Object Orienter Programming and Design Patterns through javaDive into Object Orienter Programming and Design Patterns through java
Dive into Object Orienter Programming and Design Patterns through java
 
Java.lang.object
Java.lang.objectJava.lang.object
Java.lang.object
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
Core java
Core javaCore java
Core java
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
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
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 

Polymorphism.ppt

  • 3. Polymorphism  Normally we have this when we create an object: Dog dog = new Dog();  Polymorphism allows us to also do this: Animal pet = new Dog();  The object reference variable can be a super class of the actual object type! (Does NOT work the other way around: Dog is an Animal but Animal is not necessarily a Dog)
  • 4. Where Polymorphism is Helpful  Arrays  Passing parameters  Returning values from a method
  • 5. Polymorphic Array Example Animal[] myPets = new Animal[5]; myPets[0] = new Cat(); myPets[1] = new Cat(); myPets[3] = new Dog(); for (int i = 0; i < myPets.length; i++) { myPets.feed(); } You can put any subclass of Animal in the Animal array!
  • 6. Polymorphic Arguments public class Vet { public void giveShot(Animal pet) { pet.makeNoise(); } } public class PetOwner { Vet vet = new Vet(); Dog dog = new Dog(); Cat cat = new Cat(); vet.giveShot(dog); vet.giveShot(cat); }
  • 7. Abstract Classes  Sometimes we don’t want to allow an object to be created of a certain type.  What exactly would an Animal object be?  We use the keyword abstract to prevent a class from ever being instantiated. abstract public class Animal
  • 8. Abstract Classes  Can still use abstract classes as a reference variable, for the purposes of polymorphism.  An abstract class has no use until it is extended!  A class that is not abstract is called concrete.
  • 9. Abstract Methods  An abstract method has no body and is marked with the keyword abstract. public abstract void eat();  If a method is abstract, the class it is contained in must also be abstract.  Abstract methods help the programmer to provide a protocol for a group of subclasses.  The first concrete class in the inheritance hierarchy must implement the abstract method (i.e. override it and provide it a body)
  • 10. Side Effects of Polymorphism ArrayList pets = new ArrayList(); Dog dog = new Dog(); pets.add(dog); int index = pets.indexOf(dog); Dog dog1 = pets.get(index); // won’t work Object dog2 = pets.get(index); dog2.bark(); // won’t work ((Dog)dog2).bark(); // works because of casting if (dog2 instanceof Dog) { // being careful ((Dog)dog2).bark(); } Dog dog3 = (Dog) pets.get(index); // works because of casting if (dog2 instanceof Dog) { // being careful Dog dog4 = (Dog) dog2; }
  • 11. Animal Canine Feline Wolf Dog Cat Tiger Lion Pet But remember we said that Java does not support multiple inheritance. There is a solution however: interfaces.
  • 12. Interfaces  Interface: A collection of constants and abstract methods that cannot be instantiated.  A class implements an interface by providing method implementations for each of the abstract methods defined in the interface. public class Dog extends Canine implements Pet
  • 13. Interfaces public interface Pet { public abstract void beFriendly(); public abstract void play(); } public class Dog extends Canine implements Pet { public void beFriendly() { wagTail(); } public void play() { chaseBall(); } . . . all the other Dog methods . . . } Explicitly typing in public and abstract is not necessary since they MUST be public and abstract Must implement these methods since they are in Pet
  • 14. Interfaces vs. Subclasses  Make a subclass only when you want to make a more specific version of a class.  Use an interface when you want to define a role that other classes can play, regardless of where those classes are in the inheritance tree.
  • 15. Polymorphism via Interfaces  An interface reference variable can be used to refer to any object of any class that implements that interface.  This works the same with superclasses. Pet myPet = new Dog();  The same side effects of polymorphism occur with interfaces as with inheritance.
  • 16. Comparable Interface  Defined in the java.lang package  Only contains one method: compareTo which takes an object as a parameter and returns an integer. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.  Provides a common mechanism for comparing one object to another.  http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ Comparable.html