Can anyone tell me if this code:
public class OvTester {
@Override
public int hashCode() {
return toString().hashCode();
}
}
@Override
is just compile time check if the implementer really overrides the method.
if you try overriding
@Override
public void equals(Object ob){
}
it will fail to compile
I'd like to know if this is true, and if so how it works?
No, it's not exactly true.
The @Overrides
annotation says that "this method overrides the method with the same name in the super class".
In this case the hashCode
of OvTester
overrides the hashCode
in Object
.
if its not true, then is this true: the
hashCode()
method inOvTester
must override the same name method in its superClass?
Yes. That's exactly how it works.
When one method doesn't do anything else than to call another method (almost what you got in your example) it is usually referred to as a delegate method. Perhaps that's what you're confusing this with.
That code overrides the hashCode()
method form the base Object
class.
The toString()
method still has the original implementation.
To override the toString()
, you do the following:
@Override
public String toString() {
//Your own toString() implememntation here
}
As long as the method in the child class has the same name and signature as the method in the parent class, AND the method in the parent class is NOT private it will be overidden(regardless of the presence of the annotation @Override
)
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
)
The @Override
annotation does not "determine" anything. It is simply a flag that tells the compiler to raise an error if the annotated method is not overriding a superclass or interface method. It's a tool for developers to help maintain their sanity, and nothing more.
In this specific case, it is simply noting that the hashCode()
implementation in OvTester
is overriding the hashCode()
method defined in Object
. This has nothing at all to do with toString()
, and calling the superclass's toString()
method from your hashCode()
method will not/is not the same thing as overriding toString()
.
is this true? the hashCode() method in OvTester must override the same name method in its superClass?
That is indeed true, in the sense that the annotation will cause the compiler to raise an error if there is not an overridable hashCode()
method in the superclass that matches the signature of the annotated method.
No, it will only mean that the hashCode() method is being overridden. The compiler will check at compile time that hashCode() really is a method (with that signature) that is being overridden.