Recall Subclass and Inheritance
- A subclass extends a parent class.
- Subclass inherits instance variables and methods from the parent class.
- Subclasses cannot see private components of parent class.
- Subclass can add more instance variables and methods.
- Subclass can also OVERRIDE methods.
- Consider the following assignment:
Employee e = new Manager(...)
- Question : Can we invoke
e.setSecretary
? NO (during compile time)
e
is declared to be an Employee
- And Employee does not have this method present (during compilation).
- So
e
can only refer to methods of Employee .
- Question : Can we invoke
e.bonus(p)
? YES → Which bonus()
do we use (Since Employee and Manager both have bonus()
method)?
- Since
e
is Employee , we can use all the methods in Employee class → So we can use bonus()
- So at Static : Uses
Employee.bonus()
- But during run time, the object is a
Manager
stored in an Employee object → Uses Manager.bonus()
- This is an illustration of the concept Dynamic Dispatch.
- Default in Java, optional in language like C++ (virtual function)
Polymorphism
Consider the following code:
- Defined an array of Employees in which the first object is an Employee but the second object is a Manager.
- So when calling the
bonus()
method which each element :
- It uses the correct
bonus()
function depending on whether the object is a Manager or Employee
- This is an illustration of the concept : Runtime Polymorphism or Inheritance Polymorphism
Functions, Signatures, Overloading