Stefan
Stefan

Reputation: 378

Creating an ArrayList from superclass but containing objects from extended classes

I have 3 classes. Contact, EmailContact, and PhoneContact. I want to create an Arraylist that can contain objects from both EmailContact and PhoneContact. And i need to find a way to get those objects. Here is what i have so far but It doesn't seem to split them like i wanted to.

    public void addEmailContact(String date, String email) {
        ArrayList<Contact> con = new ArrayList<>();
        con.add(new Contact(date, email));
    }

    public void addPhoneContact(String date, String phone) {
        ArrayList<Contact> con = new ArrayList<>();
        con.add(new Contact(date, phone));
    }

Upvotes: 0

Views: 729

Answers (4)

Nicholas K
Nicholas K

Reputation: 15443

Assuming this is the hierarchy :

abstract class Contact { }

class EmailContact extends Contact { }

class PhoneContact extends Contact { }

you can do the following :

List<? super Contact> myList = new ArrayList<>();
myList.add(new EmailContact());
myList.add(new PhoneContact());

The wildcard signifies that you can add any class that extends Contact to the list.

Do note that when you fetch an element from myList, the only guarantee is that it will return a type of Object. So do not try to cast it without checking the right instance of Contact otherwise you will end up with a ClassCastException.

For eg:

Object contact = myList.get(0);        
if (contact instanceof EmailContact) {
    EmailContact emailContact = (EmailContact) contact;
} else if (contact instanceof PhoneContact) {
    PhoneContact phoneContact = (PhoneContact) contact;
}

Upvotes: 0

nits.kk
nits.kk

Reputation: 5336

This is basic polymorphism in action. Reference can be of super type but it can refer to object of any sub type. The keyword new instantiates an Object. You need to provide the actual implementation with new. In your case

 Contact con = new PhoneContact(date, phone);
 Contact anotherCon = new EmailContact(date, email); 

So now with ArrayList you can do as below.

List<Contact> list = new ArrayList<>();
list.add(new EmailContact(date,email);
list.add(new PhoneContact(date,phone);

Upvotes: 0

Shiva
Shiva

Reputation: 2002

import java.util.ArrayList;
import java.util.List;

public class Contact {


    public static void main(String[] args) {
        List<? super Contact>  list = new ArrayList<>();
        list.add(new PContact());
        list.add(new EContact());

    }
}

class PContact extends Contact{

}
class EContact extends Contact{

}

Upvotes: 2

Dark Knight
Dark Knight

Reputation: 8357

Wildcards are here to help you. One can add any class that extends Contact class to a list which accepts ? super Contact

List<? super Contact> list= new ArrayList<>();
list.add(new EmailContact());
list.add(new PhoneContact());

Upvotes: 4

Related Questions