0

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

3
  • If Case1 and Case2 are methods of the same class, then they are duplicate methods, which is not allowed in Java. @Override need to be included always for the public String toString() method, since java.lang.Object contains this method and all classes inherit from java.lang.Object. Commented Mar 13, 2024 at 21:45
  • Essentially, if you think you're overriding a method of a parent class, use @Override, this provides a compile time check to ensure that you're actually doing what you think you're doing (and don't end up wondering why your code doesn't work as expected) Commented Mar 13, 2024 at 21:50
  • Thank you howlger and MadProgrammer for make clear how @Override work. Commented Mar 13, 2024 at 23:59

1 Answer 1

8

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.

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

3 Comments

Thank you. I will note that. But without the annotation. The compiler will automatic understand it and override it right? I just want to make sure
@TruongNguyen Correct, overriding happens regardless of annotation. The annotation does not cause overriding; the annotation is just a witness. Without annotation you’ll not know if you have a typo that inadvertently defines a new method rather than override.
@TruongNguyen And to add what @BasilBourque has said, this is the entire purpose of the @Override annotation. Always use it when you are intending to override the member of a superclass.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.