Home > Net >  Multiple Constuctors for same class with different parameters
Multiple Constuctors for same class with different parameters

Time:12-02

I have a Java class Book.

public class Book() {
    private List<Horror> horrorBooks;
    private List<Comedy> funnyBooks;
    
    public Book(List<Horror> horrorBooks) {
        this.horrorBooks = CollectionUtils.isNotEmpty(horrorBooks) ? horrorBooks : new ArrayList<>           ();
    }

}

I am now trying to add an additional constructor that will do the same thing but for List funnyBooks

public class Book() {
    private List<Horror> horrorBooks;
    private List<Comedy> funnyBooks;
    
    public Book(List<Horror> horrorBooks) {
        this.horrorBooks = CollectionUtils.isNotEmpty(horrorBooks) ? horrorBooks : new ArrayList<>           ();
    }

    public Book(List<Comedy> funnyBooks) {
        this.funnyBooks = CollectionUtils.isNotEmpty(funnyBooks) ? funnyBooks : new ArrayList<>           ();
    }


}

I am getting a compile error stating that both methods have same erasure

What is the most elegant way to do this? Having two constructors for the same class but one for horrorBooks and one for funnyBooks?

I was thinking I can add if / else logic but this seems like it is not the best approach to achieve what I want.

CodePudding user response:

You need to have one constructor like this:

public Book(List<?> books) {
   
}

Then you can loop through the books in the list and check what kind of book they are.

Another option is to rename your existing class to something more descriptive (e.g. BookCollection) and create a separate Book class that has a genre field and allow passing in a List<Book>, then you can check if (book.getGenre() == comedy) { // append to comedyBooks }, etc.

See similar question here - https://stackoverflow.com/a/21557178/9638991

  •  Tags:  
  • java
  • Related