Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@override annotation

Can anyone tell me if this code:

public class OvTester {
    @Override
    public int hashCode() {
        return toString().hashCode();
    }
}

determines that the toString method in the OvTester class overrides the toString method in its superclass.

I'd like to know if this is true, and if so how it works?

If it's not true, then is this true:

"the hashCode() method in OvTester must override the same name method in its superclass"

?

If that's not correct then what is correct?

like image 826
f1wade Avatar asked Aug 23 '11 11:08

f1wade


People also ask

What is use of @override in Java?

The @Override annotation denotes that the child class method overrides the base class method. For two reasons, the @Override annotation is useful. If the annotated method does not actually override anything, the compiler issues a warning. It can help to make the source code more readable.

Is it necessary to use @override in Java?

It is not necessary, but it is highly recommended. It keeps you from shooting yourself in the foot. It helps prevent the case when you write a function that you think overrides another one but you misspelled something and you get completely unexpected behavior.

What does @override mean Code?

@Override means you are overriding the base class method. In java6, it also mean you are implementing a method from an interface. It protects you from typos when you think are overriding a method but you mistyped something.

What is @override called in Java?

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.


1 Answers

Method overriding happens when you redefine a method with the same signature in a sublcass.

So here you are overriding hashCode(), not toString()

The @Override annotation is optional (but a very good thing) and indicates that this is expected to be overriding. If you misspell something or have a wrongly-typed parameter, the compiler will warn you.

So yes, the 2nd statement is true (and the superclass in this case is java.lang.Object)

like image 96
Bozho Avatar answered Sep 27 '22 16:09

Bozho