Akshit Akshit - 7 months ago 16
Java Question

Query regarding Generics with Method Overriding in Java

Case - 1

interface Test{
public void display();
}

public class TestGenerics implements Test{

@Override
public <T> void display() {
System.out.println("done");
}

public static void main(String args[]){
TestGenerics ts = new TestGenerics();
ts.display();
}
}


In Case-1, the method in the interface does not have any generic datatype but the overriden method in TestGenerics class is having a generic datatype
<T>
in method signature. This breaks the rule of method Overriding on exactly matching the method signature of display() and throws compilation error.

Case - 2

interface Test{
public <T> void display();
}

public class TestGenerics implements Test{

@Override
public void display() {
System.out.println("done");
}

public static void main(String args[]){
TestGenerics ts = new TestGenerics();
ts.display();
}
}


The Case-2, the code works fine as per the concepts of method overriding and Generics supplied in method declaration of the interface. The point to note is the Overriden method in TestGenerics class does not specify the generic type
<T>
.

The query is, why does compilation fails in Case-1 but works in Case-2 being the vice-versa of each other from the perspective of Method Overriding in Java.

Any pointers will be appreciated.

Answer

See this section from the JLS:

An instance method mC declared in or inherited by class C, overrides from C another method mI declared in an interface I, iff all of the following are true:

  • I is a superinterface of C.
  • mI is an abstract or default method.
  • The signature of mC is a subsignature (§8.4.2) of the signature of mI.

And following this section:

The signature of a method m1 is a subsignature of the signature of a method m2 if either:

  • m2 has the same signature as m1, or

  • the signature of m1 is the same as the erasure (§4.6) of the signature of m2.

With type erasure, the method signature is free of type variables:

The erasure of the signature of a generic method has no type parameters.

Comments