0

When extending an abstract class I understand why you would have to over ride some methods. But when it comes to interfaces I do not understand why it must be done. If all methods of an interface must be implemented, what is the use of overriding them?.

Im talking about the @Override annotation.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161

1 Answers1

6

Using @Override is purely optional. You don't have to use it. If you do, using @Override when implementing an interface has more or less the same reasoning as using it when extending an abstract class. In a nutshell, it prevents stupid mistakes - if an interface is changed, it forces you to change your class accordingly, instead of just tacking on the "new" methods you suddenly need to implement.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • I understand that. But wouldn't the compiler give an error if there is an unimplemented method in which case it would act as a check. – Mphiwe Ntuli Feb 11 '19 at 07:58
  • @MphiweNtuli sure, the same way it would if you're extending an abstract class. – Mureinik Feb 11 '19 at 07:59
  • 1
    @MphiweNtuli the compiler tells you when you forgot to implement a method, but it won’t tell you when a method supposed to implement a method actually doesn’t. You seem to think of implementing *n* interface methods with *n* actual methods, so a mismatch will be spotted. But what if you have *n* methods, but the interface actually has *n-1* methods? You’ve implemented all methods, but one method is not doing what it is supposed to do. With `@Override`, the compiler will tell you. – Holger Feb 11 '19 at 12:44
  • @Holger That actually makes sense. I tested it and it behaves like that. I will continue using Override then – Mphiwe Ntuli Feb 12 '19 at 07:18