Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion: @Override cannot be converted to Annotation in java?

Tags:

java

I am trying to test the @Override annotation in java. First, I overload the overloadedMethod in the Overload class, with and without parameter.

public class Overload {

    //overloaded method with and without param
    public void overloadedMethod(){
        System.out.println("overloadedMethod(): No parameter");
    }

    public void overloadedMethod(String s){
        System.out.println("overloadedMethod(): String");
    }

}

Then Override is a sub-class of the Overload class. I try to override one of the overloadedMethod. The @Override annotation is added to make sure this method is correctly override.

public class Override extends Overload{

    //now I want to override
    @Override
    public void overloadedMethod(String s){
        System.out.println("overloadedMethod(): String is overrided");
    }

    /**
     *  MAIN
     *  @param args void
     */
    public static void main(String[] args){
        Override myOverride=new Override();
        //test
        myOverride.overloadedMethod();
        myOverride.overloadedMethod("Hello");
    }
}

But an error occurred: Override cannot be converted to Annotation

/Users/Wei/java/com/ciaoshen/thinkinjava/chapter7/Override.java:20: error: incompatible types: Override cannot be converted to Annotation
    @Override
     ^
1 error

Anyone can tell me what's the problem here?

like image 965
shen Avatar asked Mar 19 '16 22:03

shen


3 Answers

The compiler thinks you try to use your class as an annotation.

Annotations share the same namespace as classes. That's why you import them with the same statements you use for importing classes. As you now have a class with the same name in the current package this class is preferred over the annotation from a different package.

You may use the annotation by its full name:

@java.lang.Override
public void overloadedMethod(String s){
    System.out.println("overloadedMethod(): String is overrided");
}
like image 101
Matthias Wimmer Avatar answered Nov 11 '22 22:11

Matthias Wimmer


Don't call the class Override or use the complete name with package :

@java.lang.Override
like image 39
Benoit Vanalderweireldt Avatar answered Nov 11 '22 21:11

Benoit Vanalderweireldt


The annotation Override is defined as

@interface Override {
....

and you have defined a class named Override too...

this is generating conflicts in the compiler because one name is related to 2 different things in the project...

rename your class to something different like MyOverride or use for the annotation the full name of the annotation.

@java.lang.Override
 public void overloadedMethod(String s){...
like image 2
ΦXocę 웃 Пepeúpa ツ Avatar answered Nov 11 '22 22:11

ΦXocę 웃 Пepeúpa ツ