【愚公系列】2022年10月 Java教学课程 04-Java语言三种注释

88 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第5天,点击查看活动详情

前言

注释就是对代码的解释和说明,其目的是让人们能够更加轻松地了解代码。注释是编写程序时,写程序的人给一个语句、程序段、函数等的解释或提示,能提高程序代码的可读性。


提示:以下是本篇文章正文内容,下面案例可供参考

一、单行注释

以“//”开头,后面接要说明的内容。使用范围没有什么规定,比如开发前,我们可以用单行注释把思路写下来,开发后,可以把局部说明写下来供后人参考。

比如我们一般在实体类的属性后面用单行注释注明(如下):

public class User implements Serializable{
 
   private String id;// 自增型ID
 
   private String username;// 用户名
 
   private String password;// 用户密码
 
}

二、多行注释

又称为块注释,可以把一部分代码块注释掉,使用范围不太清楚,但是我一般都拿来注释代码。

比如我们要注释一个判断的一部分,用多行注释就很方便(如下):

/* 我是多行注释 */
if (null != password ) {
    return "ok";
}

三、文档注释

文档注释用得比较少,但是很方便,尤其是他自带的那些标签,我个人的建议是加在认为有必要加注释的方法、类、接口、全局变量等上面,因为在Eclipse中把鼠标移动到方法上,会显示出写了文档注释的说明,很实用(如下):

import java.io.*;
 
/**
* This class demonstrates documentation comments.
* @author Ayan Amhed
* @version 1.2
*/
public class SquareNum {
   /**
   * This method returns the square of num.
   * This is a multiline description. You can use
   * as many lines as you like.
   * @param num The value to be squared.
   * @return num squared.
   */
   public double square(double num) {
      return num * num;
   }
   /**
   * This method inputs a number from the user.
   * @return The value input as a double.
   * @exception IOException On input error.
   * @see IOException
   */
   public double getNumber() throws IOException {
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader inData = new BufferedReader(isr);
      String str;
      str = inData.readLine();
      return (new Double(str)).doubleValue();
   }
   /**
   * This method demonstrates square().
   * @param args Unused.
   * @return Nothing.
   * @exception IOException On input error.
   * @see IOException
   */
   public static void main(String args[]) throws IOException
   {
      SquareNum ob = new SquareNum();
      double val;
      System.out.println("Enter value to be squared: ");
      val = ob.getNumber();
      val = ob.square(val);
      System.out.println("Squared value is " + val);
   }
}

总结

文档注释相关表格

标签描述示例
@author标识一个类的作者@author description
@deprecated指名一个过期的类或成员@deprecated description
{@docRoot}指明当前文档根目录的路径Directory Path
@exception标志一个类抛出的异常@exception exception-name explanation
{@inheritDoc}从直接父类继承的注释Inherits a comment from the immediate surperclass.
{@link}插入一个到另一个主题的链接{@link name text}
{@linkplain}插入一个到另一个主题的链接,但是该链接显示纯文本字体Inserts an in-line link to another topic.
@param说明一个方法的参数@param parameter-name explanation
@return说明返回值类型@return explanation
@see指定一个到另一个主题的链接@see anchor
@serial说明一个序列化属性@serial description
@serialData说明通过writeObject( ) 和 writeExternal( )方法写的数据@serialData description
@serialField说明一个ObjectStreamField组件@serialField name type description
@since标记当引入一个特定的变化时@since release
@throws和 @exception标签一样.The @throws tag has the same meaning as the @exception tag.
{@value}显示常量的值,该常量必须是static属性。Displays the value of a constant, which must be a static field.
@version指定类的版本@version info