Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract and concrete method with same signature in generic class

Tags:

java

In JLS 8, Section 8.4.8.1 there is a statement:

A concrete method in a generic superclass C can, under certain parameterizations, have the same signature as an abstract method in that class. In this case, the concrete method is inherited and the abstract method is not. The inherited method should then be considered to override its abstract peer from C.

Could anyone provide an example of such parametrization for generic class? I was not able to.

like image 477
nezdolik Avatar asked Jun 08 '16 10:06

nezdolik


2 Answers

Maybe

public abstract class A<T> {
    public abstract void m(T t);

    public void m(String s) {}
}

public class B extends A<String> {
}

In this case both methods in B will be void m(String).

like image 52
Roman Avatar answered Sep 21 '22 13:09

Roman


The above answer is correct given by @Roman, I want to add one more thing to that answer. If we change the parameter of method m() from String to Object, then there will be compilation error, because Generics works on Type erasure, so after type erasure m(T t) -> will be to m(Object t), which is compilation error because we cannot have two methods with same name and signature. See below compilation error -

public abstract class A<T> {
    public abstract void m(T t); // compilation error: m(T) and m(Object), both method have same erasure

    public void m(Object s) {}
}

public class B extends A<Object> {
     @Override
    public void m(Object o) {
    }
}
like image 41
pbajpai Avatar answered Sep 19 '22 13:09

pbajpai