Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

1. Overview

In this quick tutorial, we'll have a look at how to use the @Override annotation.

2. @Override Annotation

In a subclass, we can override or overload instance methods. Overriding indicates that the subclass is replacing inherited behavior. Overloading is when a subclass is adding new behavior.

Sometimes, we'll overload by accident when we actually intended to override. It's easy to make this mistake in Java:

public class Machine {
    public boolean equals(Machine obj) {
        return true;
    }

    @Test
    public void whenTwoDifferentMachines_thenReturnTrue() {
        Object first = new Machine();
        Object second = new Machine();
        assertTrue(first.equals(second));
    }
}

Surprisingly, the test above fails. This is because this equals method is overloading Object#equals, not overriding it.

We can use the @Override annotation on inherited methods to protect us from this mistake.

In this example, we can add the @Override annotation above the equals method:

@Override
public boolean equals(Machine obj) {
    return true;
}

At this point, the compiler will raise an error, informing us that we aren't overriding equals like we think.

Then, we can correct our mistake:

@Override
public boolean equals(Object obj) {
    return true;
}

Because of how easy it's to accidentally overload, it's a common recommendation to use the @Override annotation on all inherited methods.

3. Conclusion

In this guide, we saw how the @Override annotation works in Java.

The full source code for the examples can be found over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!