When should I use @Override for toString method

48 views Asked by At

I'm studying java and have a question about toString method. In both case:

//**Case1: **
@Override
public String toString(){
   return "Hello world";
}

//**Case2:** 
public String toString(){
   return "Hello world";
}

So my question is when should we need to include the @Override. Because basically the case2 is Override it already. Why we need to @Override it again.

Understanding how toString work

1

There are 1 answers

3
Tripp Kinetics On

Always use @Override on toString(), because it is always overriding Object.toString(). The annotation is simply there to tell the compiler that you intend to override a function in a superclass. That way, for example, if you misspell the name of the function and it no longer matches the function name in the superclass, the compile will fail.