Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics, interfaces and type constraints [duplicate]

given a generic interface:

public interface I<E> {
    public int interfaceMethod(E s);
}

and a generic class that implements the interface

public class A<T> implements I<T> {

    private T val;

    public A(T x) {
        val = x;
    }

    public int interfaceMethod(T val) {
        // looks like T should be of the same type as instance variable 'val'
        return 0;
    }

}

why does the following work?

public class Run {

    public static void main(String[] args) {

        A a = new A<String>("hello");

        System.out.println(a.interfaceMethod(100)); \\ returns 0
    }
}

I expected the T type parameter of the method interfaceMethod as defined in class A to constrain the method to arguments that have the same type as that supplied to the constructor of A. (in this case String).

Why does a.interfaceMethod not require an argument of type String?

like image 645
beoliver Avatar asked Oct 19 '22 07:10

beoliver


2 Answers

That happens because you ignored the warning "Raw use of parameter a" (or something like that)

Use:

A<String> a = new A<String>("hello");

When ignoring generic related warnings the code may compile when shouldn't.

like image 140
BobTheBuilder Avatar answered Nov 02 '22 07:11

BobTheBuilder


This works because a instance is typed to A class only
You should type it like this:

A<String> a = new A<String>("hello");

If you wont specify the parameter, you will be able to put there all data types like String, int etc.

like image 45
maskacovnik Avatar answered Nov 02 '22 06:11

maskacovnik