0

I am learning Java to build an android app. I see that at a lot of places, where a class is getting inherited, the over ridden methods are marked by "@Override".

For eg:

@Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

Can some one explain, how does compiler interprets this token "@Override". Is it a reserved word or a comment. Or is just the "@" that does anything special like we have "//" for commenting out.

Don Chakkappan
  • 7,397
  • 5
  • 44
  • 59
Smaxter
  • 39
  • 4

5 Answers5

1

The annotation @Override will cause an error if the method that is annotated is not from a supertype (a parent class or interface)

JLS-9.6.3.4 @Override says (in part),

If a method declaration is annotated with the annotation @Override, but the method does not override or implement a method declared in a supertype, or is not override-equivalent to a public method of Object, a compile-time error occurs.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

@Override is an annotation.

Use this so that you can take the advantage of the compiler checking to make sure you actually are overriding a method from parent class. In this way, even if you make mistakes such as misspelled a method name or not correctly matching the parameters, you will be warned by the compiler.

Abhishek
  • 878
  • 12
  • 28
1

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error.

refer this for better understanding.

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
0

From Oracle docs
@Override: @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance.

 // mark method as a superclass method
 // that has been overridden
 @Override 
 int overriddenMethod() { }

While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
0

The at sign character (@) indicates to the compiler that what follows is an annotation. In the following example, the annotation's name is Override:

@Override
void mySuperMethod() { ... }

annotation refrance

In your example @Override indicated that onCreate(Bundle savedInstanceState) method does overrides or implements a method declared in a supertype, if onCreate(Bundle savedInstanceState) not present in super class it cause error.

@Override
public void onCreate(Bundle savedInstanceState) {}
atish shimpi
  • 4,873
  • 2
  • 32
  • 50