当代码变多,甚至需要多个一起编写代码的时候,我们需要注明代码的相关信息,让其他人能更好理解代码。注释是给予提示或其他简短信息,当需要给出很多信息时,就需要文档注释,这些文字都不被执行。
一般注释
使用//标识单行注解
//把0赋值给a
int a = 0;
使用/开头,/结尾,可以编写多行注解
/*
*把0赋值给a
*再把a加1
*/
int a = 0;
a++;
有时代码里又/*分隔符,这时就不适合使用这种形式的多行注释
文档注释
用/**
开头,*/
结尾,可以进行多行注释,而且可以使用HTML标签,用java doc工具提取注释生成文档。
类注释
一般表明作者、版本、从哪个版本开始的,再就是可以写一大段文字来标明这个类的功能。
/**
* @author alex
* @version 1.0
* @see <a href="haxh.com"></>
* @since 1.0
*
*/
public class HelloWorld{
......
}
方法注释
标明参数、返回值和抛出的异常,如果没有异常就不要写,会报错
/**
*
* @param nums
* @return int
* @throws Exception
*/
public static int solution(int[] nums) {...}
属性注释
/**
*参数a为1
*/
private int a = 1;
生成文档
java doc命令可以把代码里的注释提取出来变成HTML格式的文档,可以在包所在的目录下打开命令行,输入javadoc 包名
,就自动提取出这个包的所有类的注释
如果在其他目录打开命令行,需要加上-d命令,javadoc -d 目录 包名
提取多个包的注释javadoc -d 目录 包名1 包名2
文档范例:
/**
* A <code>PrintStream</code> adds functionality to another output stream,
* namely the ability to print representations of various data values
* conveniently. Two other features are provided as well. Unlike other output
* streams, a <code>PrintStream</code> never throws an
* <code>IOException</code>; instead, exceptional situations merely set an
* internal flag that can be tested via the <code>checkError</code> method.
* Optionally, a <code>PrintStream</code> can be created so as to flush
* automatically; this means that the <code>flush</code> method is
* automatically invoked after a byte array is written, one of the
* <code>println</code> methods is invoked, or a newline character or byte
* (<code>'\n'</code>) is written.
*
* <p> All characters printed by a <code>PrintStream</code> are converted into
* bytes using the platform's default character encoding. The <code>{@link
* PrintWriter}</code> class should be used in situations that require writing
* characters rather than bytes.
*
* @author Frank Yellin
* @author Mark Reinhold
* @since JDK1.0
*/
public class PrintStream ...