Java: generic confusion inheritance

Imagine that we have the following classes:

public interface MyInterface<T> {
    List<T> getList(T t);
}

abstract class BaseClass<T extends Number> implements MyInterface<T> {
    @Override
    public List<T> getList(Number t) {
        return null;
    }
}

class ChildClass extends BaseClass<Integer> {
    @Override
    public List<Integer> getList(Integer t) {
        return super.getList(t);  //this doesn't compile
    }
}

getListin ChildClassnot compiled, output:

abstract method getList(T) in com.mypackage.MyInterface cannot be accessed directly

I cannot understand why the method is BaseClass.getListnot overridden in ChildClass.

But what completely bothers me is a fix that forces it to compile:

class ChildClass extends BaseClass<Integer> {
    @Override
    public List<Integer> getList(Integer t) {
        return super.getList((Number) t);  //Now it compiles!
    }
}

So, I drop Integer to Number and solves the problem.

Can someone explain what is going on in this code?

+3
source share
5 answers

Your base class should look like this:

abstract class BaseClass<T extends Number> implements MyInterface<T> {
    @Override
    public List<T> getList(T t) {
        return null;
    }
}

You did not use T, but the Number class as a parameter.

+5
source

, , . , .

, T .

+2

public List<T> getList(T t)

?

+2

.

 abstract class BaseClass<T extends Number> implements MyInterface<T> {
    @Override
    public List<T> getList(Number t) {
        return null;
    }
}

(T), Number MyInterface

, , . , , .

, @override.

 abstract class BaseClass<T extends Number> implements MyInterface<T> {

    public List<T> getList(Number t) {
        return null;
    }
}

, , - Number, , T, , , , . ( )

:

 abstract class BaseClass<T extends Number> implements MyInterface<T> {

    public List<T> getList(T t) { //Because T is allready restricted to be Number
        return null;
    }
}

class ChildClass extends BaseClass<Integer> {
    @Override
    public List<Integer> getList(Integer t) {
        return super.getList(t); 
    }
}

null, - . ,

 abstract class BaseClass<T extends Number> implements MyInterface<T> {

    private List<T> list = new ArrayList<T>(); //The way of initialization is up to You

    public List<T> getList() { //Because T is allready restricted to be Number
        return list;
    }

}
+1

, . , , , . , ClassCastException, , . , , , , . ClassCastException ( )

0

Source: https://habr.com/ru/post/1769737/


All Articles