Polymorphism
Polymorphism is a term from biology, in which an organism can take many forms or stages.
In Java, polymorphism allows us to use superclass references to subclass objects.
Recall the Person class hierarchy, to which we will add SoftwareDeveloper and DatabaseAdmin classes.

We can assign an Employee or DataAnalyst object to a Person reference.
Person p1 = new Employee();
Person p2 = new DataAnalyst();
This creates two objects on the heap.

Practice Exercise¶
Polymorphism is based on the "IS-A" relationship. We can assign DataAnalyst objects to Person references because DataAnalyst IS-A Person (via Employee).
When Is a Superclass Reference Useful?¶
Superclass references to subclass objects are useful for collections and methods.
Collections¶
If we have an array of superclass references, we can store subclass objects.
* This allows us to create an Employee array to store all employees in an organization, for example.
Employee[] emps = new Employee[20];
emps[0] = new DataAnalyst();
emps[1] = new SoftwareDeveloper();
Methods¶
We know we can assign a SoftwareDeveloper or DataAnalyst object to an Employee reference, because each subclass is-a Employee.
Employee persEmp = new SoftwareDeveloper();
Employee persData = new DataAnalyst();
Imagine we wanted to print the name of anyone that is-a Employee.
* Instead of a separate method for every subclass of Employee...
public void printEmpName(DataAnalyst a) {
// ...
}
public void printEmpName(SoftwareDeveloper s) {
// ...
}
public void printEmpName(DatabaseAdmin a) {
// ...
}
... we can have one method with an Employee reference parameter.
public void printEmpName(Employee e) {
System.out.println(e.getName());
}
The method does not care if the reference points to an Employee object or subtype of Employee, just that the object is-a Employee.
Drill¶
Polymorphism/com.example.polymorphism.drills.employee.EmployeePrintingApp
private void run()- Create an array of type
Employeewith space for 3 Employees- Create a
DataAnalyst,SoftwareDeveloper, andDatabaseAdminusing the multi-arg constructors for each, and add each object to the array.- Call
processEmployeesand pass theEmployeearray reference.- Add a method
printEmployeeNameAndTitlethat takes anEmployeereference and printsname - titleto the screen.public void processEmployees(Employee[] employees)- Loop through the
Employeearray and callprintEmployeeNameAndTitlefor eachEmployee.