Override method

Can you override a method in java without using annotations? Since eclipse does not support it, if you are using JRE6, you need to switch to 5 to use the @Override annotation. Will this method be canceled if I delete the annotation?

 @Override public String toString() { return name + " [" + genre + "]"; } 
+7
java
source share
3 answers

Can you override a method in java without using annotations?

Yes, the @Override annotation @Override not required to override the method.

Simply by defining a method with the same method signature of the ancestor class, it is enough to override the method.

The @Override is just a reminder to the compiler, which says that the method definition is for overriding the method.

If the method that @Override does not actually override the method, the compiler throws a compiler error - the annotation serves as an additional check of compilation time to determine whether the method definition really overrides the method.

Since eclipse does not support it, if you are using JRE6, you need to switch back to 5 to use the @Override annotation.

I use Eclipse to target Java 6 and can use the @Override annotation, so I'm not quite sure what could be causing this. Annotations are supported since Java 5 and are more closely integrated into language with Java 6.

Edit

From Andreas_D comment on the question:

smile - this simply indicates that the current baseline for your project is <1.5. This parameter is pretty independent of the JRE, you can actually use JRE 1.6 along with the source level 1.4 - and I think what happened.

It certainly looks like a compilation error may occur!

To check if the "compiler match level" is set to something in Java 5,

  • Go to Java project properties in Eclipse
  • Then go to the Java compiler menu.
  • Ensure that the compiler compliance level is set to 1.5 or higher.

Edit

Regarding the screenshot of the Gandalf StormCrow, it appears that the compiler compliance level is set lower than the JDK 1.5. By clicking on the link "Change project" and JRE up to 1.5 quick fix, correct the current situation.

The problem is that annotations were added in Java 5.

It seems that the Java project in Eclipse is currently installed, so the source code can only contain functions that were introduced before Java 5, so the use of annotations is prohibited.

The way to fix this is to tell Eclipse that you can use Java 5 features by setting the compiler compliance level to 1.5 or higher.

+8
source share

@override is just a way to make sure that if you change the contract (the method will override), this method will not compile. Without it, it will be considered as another direction.

As for JRE6, I'm not sure what you mean: annotations are supported.

Try jdk?

+3
source share

You do not need to use the @Override annotation. However, if you do this, and the method cannot override the method in the superclass, then the compiler will return an error.

0
source share

All Articles