質問

I can't understand why compiler shows an error when I try compile this code :

class A
{
    public static void f()
    {
        System.out.println("A.f()");
    }
}

class B extends A
{
    public static int f()
    {
        System.out.println("B.f()");
        return 0;
    }
}

the deference between the two methodes in A and B classes is the return type, I read that Java prevent overriding static methods. So what I expect is the compiler shouldn't show any error because there is not any overriding originally !!

役に立ちましたか?

解決

The Java Language Specification has the following rule:

8.4.8.3. Requirements in Overriding and Hiding

If a method declaration d1 with return type R1 overrides or hides the declaration of another method d2 with return type R2, then d1 must be return-type-substitutable (§8.4.5) for d2, or a compile-time error occurs.

This rule allows for covariant return types - refining the return type of a method when overriding it.

So, even if the method hides the one of the superclass and doesn't override it, the return type must still be compatible.

他のヒント

Method in class B is not overriding the method in class A, as you already know. the problem is, you have two different method visible for class B with the same signature. Remember, the return type doesn't count as a part of the signature of a method.

From JLS §8.4.2 - Method Signature:

Two methods have the same signature if they have the same name and argument types.

So, method in class B is neither a valid override, nor a valid overload. As overloading requires you to have different signature of methods, which you don't have.

Also, it is neither a valid method hiding, as that requires you to have the return type of hiding method to be same as or subtype of the return type of super class method. This is also not happening here.

So, either change the return type of class B method to void, and change it's signature.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top