Android @Override usage [duplicate] Android @Override usage [duplicate] android android

Android @Override usage [duplicate]


It's an annotation that you can use to tell the compiler and your IDE that you intend the method that has that annotation to be an override of a super class method. They have warning/errors in case you make mistakes, for example if you intend to override a method but misspell it, if the annotation is there the IDE or the compiler will tell you that it is not in fact overriding the super class method and thus you can determine why and correct the misspelling.

This is all the more important for Android applications and activities for example, where all of the calls will be based on the activity lifecycle - and if you do not properly override the lifecycle methods they will never get called by the framework. Everything will compile fine, but your app will not work the way you intend it to. If you add the annotation, you'll get an error.


This code for the beginner who really want to understand about the @Override process, this will help you! (Remind inheritance concept of Java.)

For example, the Fish class might have two subclasses: FreshwaterFish and SaltwaterFish.

These subclasses would have all the features of the Fish class, but could further customize the objects through new attributes and behaviors or modified behaviors from the parent class Fish. For example, the FreshwaterFish class might include information about the type of freshwater environment lived in (e.g. river, lake, pond, or puddle).

Similarly, the SaltwaterFish class might customize the makeBabyFish() method such that the fish eats its mate after breeding (as defined in the super class) by using the override mechanism, like this:

public class SaltwaterFish extends Fish  {      @Override      public void makeBabyFish(Fish fishSpouse, int numBabies) {          // call parent method          super.makeBabyFish(fishSpouse, numBabies);          // eat mate          eat(fishSpouse);      }  }


The Override-Annotation is just a hint for the compiler that you want to overwrite a certain function. The compiler will then check parent-classes and interfaces if the function exists there. If not, you will get a compile-error.

Its basically just a safety mechanism.

For reference, see this article (override is explained somewhere in the middle)