Java 注释

译自:https://howtodoinjava.com/core-java/basics/java-comments/

Java注释,从名字就看出,注释是在代码之间用来记录某些东西的片段。某些东西可以包括:

  • 记录变量、方法、类的信息,或者解释用法
  • 用于生成Java说明文档
  • 将不用的代码或有特殊用处的代码折叠起来,隐藏掉

注释类别

  • 单行注释
//Initialize the counter variable to 0
int counter = 0;
  • 多行注释
/*
 * This function return a variable which shall be used as counter for any loop.
 * Counter variable is of integer type and should not be reset during execution.
 */
public int getCounter() {
    //
}
  • 文档注释

javadoc工具将会摘取文档注释的内容,生成说明文档。这部分内容会在编译器自动补全时显示出来。@param和@return为javadoc的标记。

/**
  * This function return a variable which shall be used as counter for any loop.
  * Counter variable is of integer type and should not be reset during execution.
  * @param seed - initial value of counter
  * @return counter value
  */
public int getCounter(int seed) {
    //
}

性能影响

由于注释只用来阅读,并不会被编译,因此在编译后字节码(.class文件)中不会有这部分信息。因此对性能没有影响。

最佳实践

  1. 不要在源代码中保留无用的注释。如果你的代码通用的注释不能满足需要,那可能你需要重构你的代码了。
  2. 确保注释的缩进样式,保证易读性。
  3. 用简单的描述作为注释,不要过于复杂。

你可能感兴趣的:(Java)