Objectives: Essentials of Information Technology
Objectives: Essentials of Information Technology
Objectives
In this chapter, we will
• Review inheritance
Essentials of Information • Introduce polymorphism
Technology
CSE-304 N
Unit 3 : Polymorphism
1
12/29/2018
Polymorphism Polymorphism
• The implementation in the subclass overrides (replaces) the • Consider the following code:
implementation in the super class by providing a method that has same for(int i =0; i < 3; ++i)
name , same parameters or signature and same return type as the method
thePeople[i].displayDetails();
in the parent class.
• What will be output?
• The array holds references to Person objects so on the face of it the
• The version of the method that is executed will be determined by the displayDetails method from the Person class should be invoked
object that is used to invoke it. If the object of the parent class is used to
invoke the method, then the version in the parent class will be executed • The objects are not all of type Person
but if an object of the subclass is used to invoke the method then the • At run time the Java environment determines the type of object and binds
version in the child class will be executed. to the correct version of displayDetails
• This is Polymorphism
• Animal.java , Dog.java, Fish.java, Polymorphism.java
• Example : Apple.java , Food.java , Rice.java , Maggi.java
2
12/29/2018
Polymorphism Polymorphism
• Java makes use of dynamic binding with classes
– Late binding • Overloading – Which version of the method to be called is decided at
• The method to bind to is determined at run time based upon the type of compile time based on reference type
object that is actually referenced
• The alternative to this is early binding • Overriding – Which version of the method to be called is decided as run
– Static binding time based on object type.
– This is used by many other languages
– The method to bind to is determined at compile time based upon
available type information • Example TestAnimals.java
• Languages like C++ allow the programmer to choose
3
12/29/2018
– Example Student.java