Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding method with Generics

Tags:

java

I have a base class called GenericOrder that can be used to create an order with any type of products, then I have subclasses of that order that are more specific. My problem is with my ComputerOrder class and a method that I'm overriding. Here's the base class code.

import java.util.List;
import java.util.ArrayList;

public class GenericOrder<T> {

private long orderNumber;
private List<T> products;
private T theClass;

public GenericOrder() 
{
    products = new ArrayList<T>();
    orderNumber = System.currentTimeMillis();
}

public long getOrderNumber() {
    return orderNumber;
}

public void addProduct(T newProduct) {
    products.add(newProduct);

}

public int getNumberOfProducts() {
    return products.size();
}

public List<T> getProducts()
{
    return products;
}

public void setProducts(List<T> products)
{
    this.products = products;
}

public T get()
{
    return theClass;
}

public void set(T theClass)
{
    this.theClass = theClass;
}
}

And here is my subClass code. The getProducts is the method I'm having trouble with.

import java.util.ArrayList;
import java.util.List;

public class ComputerOrder<T> extends GenericOrder<T> {
    private List<ComputerPart> computerParts = new ArrayList<ComputerPart>();
    private String orderType = "Computer Parts";

public ComputerOrder() {
    super();

}

public void addProduct(ComputerPart newProduct) {

    computerParts.add(newProduct);

}

public String getOrderType() {
    return orderType;
}

public int getNumberOfProducts() {
    return computerParts.size();
}


public List<T> getProducts()
{

    return computerParts;
}


}

The Error I get says cannot convert from List(ComputerPart) to List<T>

like image 598
Michael Arnold Avatar asked Dec 06 '22 19:12

Michael Arnold


1 Answers

The error is pretty clear: getProducts() is declared to return a List<T> yet you're returning a List<ComputerPart>. I think we agree that these two are not equivalent.

Looking at your code it looks like that you actually don't want a generic class since ComputerOrder only accepts ComputerParts. What you want is something like the following:

public class ComputerOrder extends GenericOrder<ComputerPart> {
    @Override
    public List<ComputerPart> getProducts() {
        return computerParts;
    }
}
like image 190
m0skit0 Avatar answered Dec 21 '22 10:12

m0skit0