e行要在import行之前,import中标准的包名要在本地的包名之前,而且按照字母顺序排列。如果import行中包含了同一个包中的不同子目录,则应该用*来处理。
packagehotlava.net.stats;
importjava.io.*;
importjava.util.Observable;
importhotlava.util.Application;
这里java.io.*使用来代替InputStreamandOutputStream的。
Class
接下来的是类的注释,一般是用来解释类的。
/**
*Aclassrepresentingasetofpacketandbytecounters
*Itisobservabletoallowittobewatched,butonly
*reportschangeswhenthecurrentsetiscomplete
*/
接下来是类定义,包含了在不同的行的extends和implements
publicclassCounterSet
extendsObservable
implementsCloneable
ClassFields
接下来是类的成员变量:
/**
*Packetcounters
*/
protectedint[]packets;
public的成员变量必须生成文档(JavaDoc)。proceted、private和package定义的成员变量如果名字含义明确的话,可以没有注释。
存取方法
接下来是类变量的存取的方法。它只是简单的用来将类的变量赋值获取值的话,可以简单的写在一行上。
/**
*Getthecounters
*@returnanarraycontainingthestatisticaldata.Thisarrayhasbeen
*freshlyallocatedandcanbemodifiedbythecaller.
*/
publicint[]getPackets(){returncopyArray(packets,offset);}
publicint[]getBytes(){returncopyArray(bytes,offset);}
publicint[]getPackets(){returnpackets;}
publicvoidsetPackets(int[]packets){this.packets=packets;}
其它的方法不要写在一行上
构造函数
接下来是构造函数,它应该用递增的方式写(比如:参数多的写在后面)。
访问类型("public","private"等.)和任何"static","final"或"synchronized"应该在一行中,并且方法和参数另写一行,这样可以使方法和参数更易读。
public
CounterSet(intsize){
this.size=size;
}
克隆方法
2007-1-1218:44回复
220.207.106.*2楼
如果这个类是可以被克隆的,那么下一步就是clone方法:
public
Objectclone(){
try{
CounterSetobj=(CounterSet)super.clone();
obj.packets=(int[])packets.clone();
obj.size=size;
returnobj;
}catch(CloneNotSupportedExceptione){
thrownewInternalError("UnexpectedCloneNotSUpportedException:"+e.getMessage());
}
}
类方法
下面开始写类的方法:
/**
*Setthepacketcounters
*(suchaswhenrestoringfromadatabase)
*/
protectedfinal
voidsetArray(int[]r1,int[]r2,int[]r3,int[]r4)
throwsIllegalArgumentException
{
//
//Ensurethearraysareofequalsize
//
if(r1.length!=r2.length||r1.length!=r3.length||r1.length!=r4.length)
thrownewIllegalArgumentException("Arraysmustbeofthesamesize");
System.arraycopy(r1,0,r3,0,r1.length);
System.arraycopy(r2,0,r4,0,r1.length);
}
toString方法
无论如何,每一个类都应该定义toString方法:
public
StringtoString(){<