/**
* A class representing a set of packet and byte counters
* It is observable to allow it to be watched, but only
* reports changes when the current set is complete
*/
接下来是类定义,包含了在不同的行的 extends 和 implements
public class CounterSet
extends Observable
implements Cloneable
.Class Fields
接下来是类的成员变量:
/**
* Packet counters
*/
protected int[] packets;
public 的成员变量必须生成
文档(
JavaDoc)。proceted、private和 package 定义的成员变量如果名字含义明确的话,可以没有注释。
. 存取方法
接下来是类变量的存取的方法。它只是简单的用来将类的变量赋值获取值的话,可以简单的写在一行上。(个人认为尽量分行写)
/**
* Get the counters
* @return an array containing the statistical data. This array has been
* freshly allocated and can be modified by the caller.
*/
public int[] getPackets()
{
return copyArray(packets, offset);
}
public int[] getBytes()
{
return copyArray(bytes, offset);
}
public int[] getPackets()
{
return packets;
}
public void setPackets(int[] packets)
{
this.packets = packets;
}
其它的方法不要写在一行上
. 构造函数
接下来是构造函数,它应该用递增的方式写(比如:参数多的写在后面)。
访问类型("public","private" 等.)和任何"static","final"或"synchronized"应该在一行中,并且方法和参数另写一行,这样可以使方法和参数更易读。
public
CounterSet(int size)
{
this.size = size;
}
. 克隆方法
如果这个类是可以被克隆的,那么下一步就是 clone 方法:
public
Object clone()
{
try
{
CounterSet obj = (CounterSet)super.clone();
obj.packets = (int[])packets.clone();
obj.size = size;
return obj;
}
catch(CloneNotSupportedException e)
{
throw new InternalError("Unexpected CloneNotSUpportedException: "
+ e.getMessage());
}
}
. 类方法
下面开始写类的方法:
/**
* Set the packet counters
* (such as when restoring from a database)
*/
protected final
void setArray(int[] r1, int[] r2, int[] r3, int[] r4)
throws IllegalArgumentException
{
//
// Ensure the arrays are of equal size
//
if (r1.length != r2.length || r1.length != r3.length || r1.length != r4.length)
throw new IllegalArgumentException("Arrays must be of the same size");
System.arraycopy(r1, 0, r3, 0, r1.length);
System.arraycopy(r2, 0, r4, 0, r1.length);
}
. toString 方法
无论如何,每一个类都应该定义 toString 方法:
public
String toString()
{
String retval = "CounterSet: ";
for (int i = 0; i < data.length(); i++)
{
retval += data.bytes.toString();
retval += data.packets.toString();
}
return retval;
}
. main 方法
如果main(String[]) 方法已经定义了, 那么它应该写在类的底部.
四、函数编写风格
. 函数的命名
通常,函数的命名也是以能表达函数的动作意义为原则的,一般是由动词打头,然后跟上表示动作对象的名词,各单词的首字母应该大写。另外,还有一些函数命名的通用规则。如取数,则用Get打头,然后
跟上要取的对象的名字;设置数,则用Set打头,然后跟上要设的对象的名字;而对象中为了响应消息进行动作的函数,可以命名为On打头,然后是相应的消息的名称;进行主动动作的函数,可以命名为Do打头,然后是相应的动作名称。类似的规则还有很多,需要程序员多读优秀的程序,逐渐积累经验,才能作出好的函数命名。
. 函数注释
系统自动生成的函数,如鼠标动作响应函数等,不必太多的注释和解释;
对于自行编写的函数,若是
系统关键函数,则必须在函数实现部分的上方标明该函数的信息,格式如下:
/**
* 函数名: