Friday 27 June 2014

@Override

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.

Use it every time you override a method to detect bugs early.

For Example
public class SuperClass {
 public void print(){
 
 }
}

import java.lang.annotation.Annotation;

public class SubClass extends SuperClass{    
 @Override
    public void Print(){
 
 }
}

When you tries to compile the above program below error thrown.

SubClass.java:4: error: method does not override or implement a method from a supertype
        @Override
        ^
1 error

Since Print method in SubClass.java actually not overriding the method in SuperClass.java. Becaue the method Print in SubClass.java starts with Capital 'P' where as SuperClass.java starts with small 'p'.

Now change the method name in SubClass.java and recompile.

import java.lang.annotation.Annotation;

public class SubClass extends SuperClass{    
 @Override
    public void print(){
 
 }
} 




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment