Can a class have two no-args methods with same name?

Barat Sahdzijeu :

Reading documentation:

https://docs.oracle.com/javase/9/docs/api/java/util/ServiceLoader.html

I was confused by this sentence:

The service provider class file has more than one public static no-args method named "provider".

Assuming JavaDoc is correct, and assuming that static members are not inherited, how this might be possible in Java? Or it's an error in JavaDoc?

Andreas :

how this might be possible in Java?

It is not, since method signatures must be unique, and the signature is the method name and parameter types.

Except, that is not how the JVM works, only how Java works.

The JVM includes the return type as part of the signature, so technically a class can have multiple methods with the same name and parameters, but different return types.

So it can definitely happen for classes written in other JVM languages, but can it happen for a Java class?

Yes it can, when you have covariant return types for overridden methods. See Can overridden methods differ in return type?

Given the example in that answer, what really happens is this fake code:

class ShapeBuilder {
    ...
    public Shape build() {
    ....
}

class CircleBuilder extends ShapeBuilder{
    ...
    @Override
    public bridge Shape build() { // override matches full JVM signature
        return <Circle>build(); // call other method with different return type
    }
    public Circle build() {
    ....
}

The "bridge" method is a hidden method generated by the compiler to make the difference between Java and the JVM work correctly.

FYI: In that aspect, "bridge" methods are similar to "synthetic" methods, which are generated by the compiler to allow outer classes access to private members of inner classes, or vice versa.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164206&siteId=1