2

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 !!

2
  • 1
    It is not overriding check the rules of overriding .... first f method returns void() second f method returns int Commented Feb 15, 2014 at 12:18
  • 1
    Yes, but the compiler tell that there is an error ??! Commented Feb 15, 2014 at 12:19

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

This is not overloading, it's hiding. because of static

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.