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?
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.
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.
@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.
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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With