Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Override return type of subclass on Java

I’m learning about Java. I would like to override the return type of ArrayList to subclass. Is it possible?
The compiler said that can override only the same type…

unit classes

import java.util.ArrayList;

abstract public class BaseUnit {
  public BaseUnit() {
  }

  public abstract ArrayList<BaseElement> getList();
}

public class UnitA extends BaseUnit {
  private ArrayList<ElementA> listA;

  UnitA() {
    super();
    listA = new ArrayList<ElementA>();
    listA.add(new ElementA());
  }

  public ArrayList<ElementA> getList() {
    return listA;
  }
}

element classes

public class BaseElement {
  protected String name = "";
  public BaseElement() {

  }
  
  public void sayName() {
    System.out.println(name);
  }
}

public class ElementA extends BaseElement {
  public ElementA() {
    name = "A";
  }
}

main

public static void main() {
  UnitA unitA = new UnitA();
  unitA.getList().get(0).sayName();
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The generics of the list in both types have to be the same. For what you want to do you basically have two options: Use the extends keyword, or make the type in the base class totally generic.

The first solution would look like this:

import java.util.ArrayList;

abstract public class BaseUnit {
  public BaseUnit() {
  }

  public abstract ArrayList<? extends BaseElement> getList();
}

The second like this:

import java.util.ArrayList;

abstract public class BaseUnit<K> {
    public BaseUnit() {
    }

     public abstract ArrayList<K> getList();
}

public class UnitA extends BaseUnit<ElementA> {
    private ArrayList<ElementA> listA;

    UnitA() {
        super();
        listA = new ArrayList<ElementA>();
        listA.add(new ElementA());
     }

    public ArrayList<ElementA> getList() {
        return listA;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading