java 注解 @Override

目录

    • 一 笔记
    • 二 Override源码
    • 三 使用@Override注解

一 笔记

@Override 专门给编译器参考的;带有Override编译器在编译时都会进行检查;检查这个方法是否重写了父类的方法,

  • 如果不是重写了父类的方法,编译器会自动报错;
  • 注解的作用:1、做编译检查的;2、被反射机制解析;
  • @Override 只能标注方法,不能标注类;

二 Override源码

/*
 * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.lang;

import java.lang.annotation.*;

/**
 * Indicates that a method declaration is intended to override a
 * method declaration in a supertype. If a method is annotated with
 * this annotation type compilers are required to generate an error
 * message unless at least one of the following conditions hold:
 *
 * 
  • * The method does override or implement a method declared in a * supertype. *
  • * The method has a signature that is override-equivalent to that of * any public method declared in {@linkplain Object}. *
* * @author Peter von der Ahé * @author Joshua Bloch * @jls 9.6.1.4 @Override * @since 1.5 */
@Target(ElementType.METHOD) @Retention(RetentionPolicy.SOURCE) public @interface Override { }

三 使用@Override注解

public class AnnotationTest02 extends Object{
//    检查是否有重写父类的方法;检查到没有重写,就会报编译错误;
    @Override
    public String toString(){
        return "AnnotationTest02";
    }
}

你可能感兴趣的:(java,java,开发语言)