Course contentsShow
← Java
Lesson 535 of 2,87013. The Object Class and Common MethodsFree lesson

Overriding toString: Basic Syntax

Write your first toString override with proper signature and the @Override annotation.

Overriding toString: Basic Syntax

You'll learn: How to write your own toString method with the correct signature and annotation.

The Core Idea

Every class inherits toString from Object, but the default implementation just prints the class name and a hash code—not very useful. To provide meaningful output, you override the method by writing your own version. This requires getting the method signature exactly right and signaling your intent with the @Override annotation.

The Required Signature

Your toString override must match the signature from Object:

public String toString()
  • public — same visibility as the original
  • String — the return type (cannot change)
  • toString() — exact method name, no parameters

Using the @Override Annotation

Always include @Override above your method. This tells the compiler you're intentionally overriding a parent method. If you make a typo or get the signature wrong, the compiler will catch it immediately.

public class Book {
    private String title;
    private String author;
    
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
    
    @Override
    public String toString() {
        return "Book: " + title + " by " + author;
    }
}

Now when you print a Book object or use it in string concatenation, you'll see "Book: 1984 by George Orwell" instead of "Book@15db9742".

Why the @Override Annotation Matters

Think of @Override as a safety net. Without it, if you accidentally write public String tostring() (lowercase 's'), Java would compile it as a new method instead of an override—and you'd never see your custom output. With @Override, the compiler prevents this silent mistake.

Key Takeaway: Override toString using the exact signature public String toString() with the @Override annotation to provide meaningful string representations of your objects.