注释是程序中未执行的部分。编译器只是忽略注释,因为它们不是为此而设计的。它们是用“人类”语言编写的,旨在为开发人员或参与开发的人员解释程序、程序的一部分、一行或方法。大多数情况下,评论都是用英语写的,这是一种传统。在本文中,我们将讨论 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 课程中的视频课程
GO TO FULL VERSION