aki
aki

Reputation: 1761

how to create class that that has a list in it, and the list should contain two different kind of objects

For example:

I have two type of objects:

public class Image {
...
}

And

public class Video {
...
}

I want to have a class that will contain a single list of those two objects, like this:

public class Media {

private List<Object> mediaList = new....
....
}

Upvotes: 1

Views: 128

Answers (2)

Jonathan Payne
Jonathan Payne

Reputation: 2223

Create a parent class, and have Image and Video be children of it.

You can then make the list of the parent type.

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

public class Example
{
    public abstract ImageVideo
    {

    }

    public class Image extends ImageVideo
    {

    }

    public class Video extends ImageVideo
    {

    }

    public static class Media
    {
        public static void main( String args[] )
        {
            Image image = new Example().new Image();
            Video video = new Example().new Video();

            List<ImageVideo> mediaList = new ArrayList<ImageVideo>();

            mediaList.add( image );
            mediaList.add( video );
        }
    }
}

Also, the following compiles, you would just have to cast the objects back when you retrieve them from the list.

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

public class Example
{
    public class Image
    {

    }

    public class Video
    {

    }

    public static class Media
    {
        public static void main( String args[] )
        {
            Image image = new Example().new Image();
            Video video = new Example().new Video();

            List<Object> mediaList = new ArrayList<Object>();

            mediaList.add( image );
            mediaList.add( video );
        }
    }
}

Upvotes: 3

danieltorres
danieltorres

Reputation: 370

Create a parent Class.

 public abstract Class MediaFormat{
}

and then the child classes

    public class Image extends MediaFormat{
...
}

    public class Video extends MediaFormat{
...
}

then finally

    public class Media {
     private List<MediaFormat> mediaList = new List<MediaFormat>();
     ...
}

The parent class (MediaFormat) is abstract.That way you make sure that MediaFormat cannot be instantiated.

Upvotes: 0

Related Questions