简体   繁体   中英

Abstract and concrete method with same signature in generic class

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.

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) .

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) {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM