【发布时间】:2011-10-09 10:42:58
【问题描述】:
我正在编写一个简单的接口类,如下所示。我只需要将其中一种方法提供给用户。使用这个类的用户只需要这个特定方法的返回值(checkLink)。因此,我单独将此方法声明为受保护的,因此它仅对调用Iface 类的用户可见。由于类中的其余方法将在类中使用,因此它们被声明为私有。我添加了静态关键字,因为这些方法有点“无状态”。我对类变量使用了 static final 关键字,因为我想要像 #define 这样的 C 语言。
由于我是 C 程序员,我对 Java 世界还是陌生的。请看一下我的代码框架,并告诉我所做的声明是否正确传达了含义。
package com.prog.Test;
import java.net.*;
import java.io.*;
public class Iface{
private static final int MSG_OK = 0x01;
private static final int MSG_NOK = 0x00;
private static final int MSG_FAIL = 0xFF;
private static byte[] getBytesFromUrl(URL link) throws IOException {
......
return bytes;
}
private static int[] msg_header(byte[] msg) throws Exception
{
int len = msg.length;
System.out.println("len ="+len);
int[] headerMsg =new int [3];
headerMsg[0]= MSG_OK;
......
return headerMsg;
}
private static byte[] Tobyte(int[]src) {
....
}
protected static int checkLink (URL url ) throws IOException {
byte[] rbuffer = null;
byte[] hdr = null;
int status = -1;
try{
rbuffer = getBytesFromUrl(url);
..
..
hdr = Tobyte(msg_header(rbuffer));
...
...
status = 0;
}catch (Exception e) {
System.err.println("Exception: " + e);
}
return status;
}
}
所以当我在应用程序中使用这个Iface 类时,我这样称呼它:
public class Trial {
public static void main (String [] args ) throws IOException {
URL url = new URL("http://localhost:8000/myfile");
System.out.println("Calling Iface");
int retval = Iface.checkLink(url);
System.out.println("retval ="+retval);
}
}
我也试过这个(在删除checkLink() 方法中的static 关键字之后):
public class Trial {
public static void main (String [] args ) throws IOException {
URL url = new URL("http://localhost:8000/myfile");
System.out.println("Calling Iface");
Iface callInterface;
int retval = callInterface.checkLink(url);
System.out.println("retval ="+retval);
}
}
有区别吗?
【问题讨论】:
-
有错误吗?还是这只是代码审查?
-
我以为我偶然发现了书评