Home > front end >  Returning child type generic to parent type generic in java
Returning child type generic to parent type generic in java

Time:10-14

I went through a lot of questions related to this and I couldn't clinch my issue. My question is as bellow.

I have a parent abstract class.

public class abstract Parent{ }

I have another two child classes which are extended from the above parent class.

public class ChildOne extends Parent{}
public class ChildTwo extends Paretn{}

In another class, I am using these three classes as bellow.

public class A{ 
   public List<ExcelRecord<Parent>> getExcelRecords(){
      ChildOne childone = new ChildOne();
      List<ExcelRecord<ChildOne>> list = new ArrayList();
      //few logics

      return list; //**compilation here**
   }
}

compilation issue is: required: List<ExcelRecord> provided: ist<ExcelRecord>

I need to return child type generic to parent type generic. How can I achieve this?

update. The returned value of this method is going to use in the legacy method which can't be altered accordingly.

CodePudding user response:

Use wildcards in your return type. This wildcard will accept any class that extends the Parent class


public List<ExcelRecord<? extends Parent>> getExcelRecords() {
   //...
}

Feel free to check out the Java Generics FAQ for more details

CodePudding user response:

If you cannot alter the return type you can only alter the returned value.

Therefore simply alter the type of your local variable:

List<ExcelRecord<Parent>> list = new ArrayList<>();
                  ^relevant change             ^also add Diamond 
                                               operator to give 
                                               the ArrayList a 
                                               concrete type

The ExcelRecord can only be of the generic type Parent since that's what you declared in the method header.

  • Related