I have an abstract super class called Recipient
and two child classes OfficialRecipient
and PersonnelRecipient
. OfficialRecipient
has a child class OfficeFriendRecipient
. I also have defined class InputOutput
which has a method UpdateFile
. Here Recipient
class has methods getName ()
, getEmail ()
, and OfficialRecipient
has method getDesignation ()
.
I have an array list defined as follows:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
List <OfficialRecipient> official = new ArrayList<>();
When I try to write the following code, java is showing error. The error is rectified when I cast pointer to OfficialRecipient
.
Iterator <Recipient> pointer = official.iterator();
while (pointer.hasNext()) InputOutput.UpdateFile("official", pointer.getName (), "null", pointer.getEmail (), pointer.getDesignation (), "null", filePath);
My question is why a superclass pointer could not handle a subclass official
list. Isn't it what polymorphism supposed to do?
I've just started studying java and couldn't understand this concept. Please briefly explain.
The code compiles correct when writing like this:
Iterator <OfficialRecipient> pointer = official.iterator();
while (pointer.hasNext()) InputOutput.UpdateFile("official", ((Recipient) pointer).getName (), "null", ((Recipient) pointer).getEmail (), ((OfficialRecipient) pointer).getDesignation (), "null", filePath);