Write a simple Interface (with nothing in it) called Child and use it to create an ArrayList that can store instances of Boy and Girl only

CY1223 :

I am answering a revision question and I'm kinda stuck on how to answer it.

The Question goes like this:

Suppose we have the following class definition outlines:

public abstract class Person { ... }

public class Man extends Person { ... }

public class Woman extends Person { ... } 

public class Boy extends Person { ... } 

public class Girl extends Peron { ... }

i. Create an ArrayList that can store any instance of the classes Man/Woman/Boy/Girl using the above class definitions, but will not allow instances of Animal or any other classes.

ii. Write a simple Interface (with nothing in it) called Child and use it to create an ArrayList that can store instances of Boy and Girl only (i.e. and not Man or Woman).

The 1st I assume the answer is the one below.

ArrayList <Person> list = new ArrayList<Person>();

But for the 2nd part of the question I'm not sure how to answer it. I assume it has something to do with Java generics.

lealceldeiro :

I would create the Child interface.

interface Child {}

Make Boy and Girl implement it.

public class Boy extends Person implements Child { ... }

public class Girl extends Person implements Child { ... }

And then use the interface as generic type for the list.

ArrayList<Child> list = new ArrayList<>();

Side note

Always try to program to interfaces. Instead of ArrayList as reference use List.

List<Child> list = new ArrayList<>();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=128241&siteId=1