简体   繁体   中英

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....
....
}

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 );
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM