CodeGym /Java Blog /Toto sisi /Java 評論
John Squirrels
等級 41
San Francisco

Java 評論

在 Toto sisi 群組發布
註釋是程式中未執行的部分。編譯器只是忽略註釋,因為它們不是為此而設計的。它們是用「人類」語言編寫的,旨在為開發人員或參與開發的人員解釋程式、程式的一部分、一行或方法。大多數情況下,評論都是用英語寫的,這是一種傳統。在本文中,我們將討論 Java 中的註釋以及如何正確使用它們以使您和您的隊友的生活更輕鬆。

Java 註解:為什麼它們很重要

他們說程式設計師在評論自己的程式碼時非常懶惰。然而,這是一項非常重要的技能,所以不要低估它,即使您剛開始學習 Java。註解良好的程式碼比沒有註解的程式碼更有價值,因為這樣的程式更容易維護。由於大型專案通常是用 Java 編寫的,因此有效的註解也可以加快開發速度,因為程式設計師可以更輕鬆地處理其他人的程式碼。需要評論以便:
  • 了解代碼。你的或別人的。如果您覺得不需要破解自己的程式碼,因為您自己編寫了程式碼,請嘗試打開您一個月前甚至更早編寫的相對複雜的程序,并快速了解您的想法、地點和原因。註釋可用於解釋程式或程式區塊的邏輯,並為以後使用您的程式碼的人員留下建議。這種類型的評論可以稱為解釋性的。

  • 包含有關物件用途、輸入和輸出參數(如果有)、有關開發人員的資料以及與程式碼片段相關的其他重要資訊的資訊。此類註釋位於模組、函式庫、流程和函數的標題中。它們可以稱為文檔註釋。

  • 控制錯誤並改進程式碼。有問題的程式碼或需要改進的程式碼始終可以被註解掉並在以後重新訪問。如果您想到某個問題可以用不同的方式解決,但現在您沒有時間,請在評論中寫下這個想法。否則,很可能在新程式碼的壓力下,您會忘記它。

Java 中的註解類型

儘管您可以在註釋中編寫任何內容,但 Java 中有某些類型的註釋以及使用它們的規則。Java 中的註解是:
  • 單行註解
  • 多行註解
  • 文件註釋

單行註解

最常見的 Java 註解是單行註解。為了表示這樣的註釋,在文字//之前添加雙斜線就足夠了。單行註解僅在註解的開頭標記。評論持續到行尾。句法:
//here is a single line comment.
讓我們舉一個這類 Java 註解的範例:
public class CommentsDemo1 {
   public static void main(String[] args) {
       System.out.println("This text is visible for Java compiler");
       //this text is single line comment
//This one is also single line comment
//they both (and me) are invisible for compiler
   }
}
輸出是:
該文本對於 Java 編譯器是可見的
通常單行註解位於程式中註解位置的上方或下方,有時位於同一行。重要的是,評論所指的內容在視覺上清晰可見。

多行註解

有時沒有足夠的一行來寫 Java 註解。例如,您需要描述方法的工作原理或您正在實現的複雜公式。在這種情況下,您可以編寫多個單行註釋,但編寫所謂的多行註釋會更合理。它們的兩側都標有符號/* */。多行註解的語法:
/*This comment
is
Multi line comment
we can describe here
what we need */
讓我們來看一個程式碼中多行註解的例子
public class RleTest {

   /*
   Run Length Encoding (RLE),  a data compression algorithm
   that replaces repeated characters (series)
   with one character and the number of its repetitions.

   this method is to decode a String using run-length encoding

    */
   private static String decodeRle(String encoded) {
       if (encoded.isBlank()) return "";
       StringBuilder result = new StringBuilder();
       int count = 0;
       char baseChar = encoded.charAt(0);
       for (int i = 1; i <= encoded.length(); i++) {
           char c = i == encoded.length() ? '$' : encoded.charAt(i);
           if (Character.isDigit(c)) {
               count = count * 10 + Character.digit(c, 10);
           } else {
               do {
                   result.append(baseChar);
                   count--;
               } while (count > 0);
               count = 0;
               baseChar = c;
           }
       }
       return result.toString();
   }
   public static void main(String[] args) {
       System.out.println(decodeRle("C3ecddf8"));
   }
}

Java 文件註釋

這是一種特殊類型的 Java 註釋,用於產生文件頁面。通常開發人員使用 Javadoc 編寫文件註釋,Javadoc 是一個文件產生器,用於從 Java 原始碼產生 HTML 格式的 API 文件。Javadoc 使用的文件格式是記錄 Java 類別的業界標準,最受歡迎的 IDE(例如 IntelliJ IDEA 和 Eclipse)會自動產生 Javadoc HTML。Java 文件註解的語法如下:
/**
Some important Javadoc comments here
You don’t know it yet, but Javadoc rulez

@author  Java Developer
*/
這是一個例子:它是 Java Short類別的片段。順便說一句,您可以從 IDE 查看任何 Java 類別程式碼(例如,在 Windows 中的 IntelliJ IDEA 中,只需在任何類別或方法的名稱上按 ctrl+LBM 或 ctrl + b(在 Windows 中))。
package java.lang;

import jdk.internal.HotSpotIntrinsicCandidate;
import jdk.internal.misc.VM;

/**
* The {@code Short} class wraps a value of primitive type {@code
* short} in an object.  An object of type {@code Short} contains a
* single field whose type is {@code short}.
*
* <p>In addition, this class provides several methods for converting
* a {@code short} to a {@code String} and a {@code String} to a
* {@code short}, as well as other constants and methods useful when
* dealing with a {@code short}.
*
* @author  Nakul Saraiya
* @author  Joseph D. Darcy
* @see     java.lang.Number
* @since   1.1
*/
public final class Short extends Number implements Comparable<Short> {

   /**
    * A constant holding the minimum value a {@code short} can
    * have, -2<sup>15</sup>.
    */
   public static final short   MIN_VALUE = -32768;

   /**
    * A constant holding the maximum value a {@code short} can
    * have, 2<sup>15</sup>-1.
    */
   public static final short   MAX_VALUE = 32767;

   /**
    * The {@code Class} instance representing the primitive type
    * {@code short}.
    */
   @SuppressWarnings("unchecked")
以下是眾所周知且深受所有新手喜愛的println()方法的 Java 程式碼,並附有這樣的註解:
/**
* Prints a String and then terminate the line.  This method behaves as
* though it invokes {@link #print(String)} and then
* {@link #println()}.
*
* @param x  The {@code String} to be printed.
*/
public void println(String x) {
   if (getClass() == PrintStream.class) {
       writeln(String.valueOf(x));
   } else {
       synchronized (this) {
           print(x);
           newLine();
       }
   }
}
Javadoc 有一些用 @ 標記的特殊 Javadoc 標籤,您可以在上面的程式碼中看到。此類 Javadoc 標記的範例是 @author,它添加了類別作者的名稱。另一個 Javadoc 標記是 @since,它添加了一條註釋,表明從指定的 Java 版本開始使用此類。編寫好的 Javadoc 文件需要知識和經驗(還有耐心!)。您可以在官方文件How to Write Doc Comments for the Javadoc Tool 中找到有關 Javadoc 的更多資訊。

PS一些來自現實生活的有趣評論例子

/**
*Dear Maintainer
*
*Once you are done trying to 'optimize' this routine,
*and you have realized what a terrible mistake that was,
*please increment the following counter as a warning
*to the next guy.
*
*total_hours_wasted_here = 73
*/
Exception up = new Exception("Something is really wrong.");
throw up;  //ha ha
// When I wrote this, only God and I understood what I was doing
// Now, God only knows
// sometimes I believe compiler ignores all my comments
/**
Always returns true.
*/
public boolean isAvailable() {
return false;
}
為了鞏固您所學到的知識,我們建議您觀看我們的 Java 課程中的影片課程
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION