1.14.1 The Built-In Annotations 内建注解
Java defines seven built-in annotations.
Four are imported from java.lang.annotation: @Retention, @Documented, @Target, and @Inherited.
Three, @Override, @Deprecated, and @SuppressWarnings, are included in java.lang.
Java定义了 7 种内建注解:
其中 4 种从 java.lang.annotation导入:
@Retention
@Documented
@Target
@Inherited
另外3中包含在java.lang中:
@Override
@Deprecated
@SuppressWarnings
1.14.2 Standard Annotations: Override
Override is a marker annotation type that can be applied to a method to indicate to the compiler that the method overrides a method in a superclass. This annotation type guards the programmer against making a mistake when overriding a method. For example, consider this class Parent:
@Override 是标记型注解, 可以应用于方法, 指示编译器该方法覆盖父类的一个方法.
此注解防止编程者在覆盖一个方法时犯错. 例如: 下面的代码编译不通过, 因为父类中没有相同的方法签名.
class Parent { public float calculate (float a, float b) { return a * b; } } //Whenever you want to override a method, declare the Override annotation type before the method: public class Child extends Parent { @Override public int calculate (int a, int b) { return (a + 1) * b; } }
1.14.3 Standard Annotations: Deprecated 不推荐, 藐视
Deprecated is a marker annotation type that can be applied to a method or a type (class/interface) to indicate that the method or type is deprecated.
@Deprecated 是 标记型注解, 可用于方法或类/接口, 指示该方法或类型不被推荐.
If you use or override a deprecated method, you will get a warning at compile time.
如果你使用或覆盖一个不推荐的方法, 在编译时会收到一个警告.
public class DeprecatedTest2 { public static void main(String[] args) { DeprecatedTest test = new DeprecatedTest(); test.serve(); } } class DeprecatedTest { @Deprecated public void serve() { } }