Implementing a generic list that can contain multiple data types in Java / JavaFX

I need to develop a list of libraries that will contain several types of libraries. For example, a library can be a video library or a photo library. I want to follow the MVC design pattern using JavaFX, if that matters. See the UML diagram below with a link to my question:

Picture 1

enter image description here

So, I figured that for a list in my library model, I would use a generic type:

public class LibraryModel<T> {
    private List<T> aList;
}

      

However, this won't work because when I instantiate the list of libraries I need to specify the type. This way I can only list a photo or video library as a list, not both.

I tried to introduce a generic type called "Library" to be listed (as a superclass) to be extended with PhotoController / VideoController:

Figure 2 enter image description here

public class LibraryModel {
    private List<Library> aList;
}

      

In Figure 2, I can create a list of shared libraries. But how does this affect my ability to perform certain photo / video tasks? Suppose I have the following methods:

Superclass methods:

displayAll()
add()
remove()

      

Library library methods:

displaySlideShow()

      

Video library methods:

playVideo()

      

By keeping the libraries as a superclass, how can I call specific methods of other types of libraries? Is it even legal?

Please say goodbye to me, I am still learning Java, thanks in advance.

+3


source to share


1 answer


Use an abstract class

Library.

abstract class Library {

}

      

then create child classes.

photo library.

class PhotoLibrary extends Library {

     displaySlideShow(){

     }   
}

      



video library.

class VideoLibrary extends Library {

        playVideo() {

        }

}

      

in the main class or else, you can use them.

private List<Library> aList;
aList.add(new PhotoLibrary());
VideoLibrary l2 = new VideoLibrary();
aList.add(l2);

      

then you can call the available methods using

Library l = aList(i);
if(l instanceof PhotoLibrary) {
     PhotoLibrary pl = (PhotoLibrary)l;
     pl.displaySlideShow();
}
else if(l instanceof VideoLibrary) {
     VideoLibrary vl = (VideoLibrary)l;
     vl.playVideo();
}

      

+3


source







All Articles