0

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);
  • You're asking about an error thrown by some code, but we don't know what the error is, and we don't know what the code is either. Post the relevant code, and the exact and complete error message. – JB Nizet Sep 29 '18 at 18:38

1 Answers1

0

The code you show is not valid. If pointer is an Iterator instance, then you cannot access the methods of Recipient using pointer. You need first to get the next element by calling Recipient recipient = pointer.next(). Then you are able to call the methods of Recipient using the variable recipient - not pointer.

recipient.getDescription() would not work because getDescription() is not declared at the class Recipient. But if you get the next element from the second Iterator<OfficialRecipient> like OfficialRecipient recipient = pointer.next() then recipient is of type OfficialRecipient where getDescription() is defined. Thus you can call recipient.getDescription(). The cast is then not necessary.

Summarizing:

  • An Iterator<T> will provide you the next element of T but is not an instance of T. @see: How do I iterate and modify Java Sets?
  • Second point is the question linked above for which this question is already marked as duplicate.
LuCio
  • 5,055
  • 2
  • 18
  • 34