Skip to content Skip to sidebar Skip to footer

Why @override Needed In Java Or Android?

In java or Android there are @Override annotations. What does it mean? I found that it is used when method is from subclass or inherited interface's method, I want to know further

Solution 1:

This question is also answered here, and quite succinctly: Android @Override usage

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.

In other words, if you add @Override this helps you make sure you are really overriding an existing method! Pretty darn useful.

Solution 2:

Overriding means that you are changing the behavior of a method inherited from a parent class, without changing the signature. The @Override annotation is used to mark this. It is strongly linked with the concept of polymorphism. Example:

publicclassA {
    publicvoidfoo() {
        System.out.println("A");
    }
}

publicclassBextendsA {

    @Overridepublicvoidfoo() { // I want to change the way foo behavesSystem.out.println("B"); // I want to print B instead of A
    }
}

publicstaticvoidmain(String[] args) {
    A a = newA();
    a.foo(); // prints A

    A b = newB(); // I can use type B because it extends A
    b.foo(); // I have overriden foo so it prints B now
}

Solution 3:

Just to ensure that you are actually overriding it at compile time, and to improve readability

Example:

classAnimal{
  publicvoideat(Food food){
  }
}

classPersonextendsAnimal {
  @Overridepublicvoideat(String food){
  }

}

This will give you compile time error since you are not actually overriding it (see the type of food)

Solution 4:

@override its an annotation i.e meta data introduce in jdk 1.6 . If you don't write it before override method , it won't make any difference but it just use to increase the readability of compiler.

Solution 5:

To mark that you really implement or change a method. Like meantined it's checked at compile time. That is you for instance you get an error if you want to implement @Override public void equals(final Car pObject); instead of @Override public void equals(final Object pObject);.

Post a Comment for "Why @override Needed In Java Or Android?"