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?
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");
}
Don't call the class Override or use the complete name with package :
@java.lang.Override
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){...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With