我必须实现一个 RMI 服务器,它将成为另外两个 RMI 服务的前端。所以我决定做一个合乎逻辑的事情是让这个接口(interface)实现其他两个服务的接口(interface)。
public interface FrontEndServer extends Remote, BookServer, StudentServer
{
// Block empty so far
}
但是StudentServer上有一个方法
/**
* Allows a student to borrow a book
*
* @param studentID of the student who wishes to borrow a book
* @param bookID of the book the student wishes to borrow
* @throws RemoteException
* @throws StudentNotFoundException when a student is not found in the system
*/
void addBookToStudent(int studentID, int bookID) throws RemoteException, StudentNotFoundException;
我希望 FrontEndServer
也抛出一个 BookNotFoundException
,因为该服务还将在尝试添加详细信息之前验证该书是否确实存在。
这是可能的还是我的设计理念完全偏离,这实际上是一个糟糕的设计理念,就好像其他界面都发生了变化一样?我是否会更好地为 FrontEndServer
中的所有方法编写方法签名?
最佳答案
如果您扩展一个接口(interface)(如果您实现一个接口(interface)同样适用),您不能重写一个方法并让它抛出比原始方法更多的已检查异常。你可以抛出相同或更少但不能更多。
想想看:
interface A {
void foo();
}
interface B extends A {
void foo() throws IOException;
}
A a = new B() { ... }
a.foo();
可能会抛出 IOException 但您无从知晓。这就是为什么你不能这样做。
这当然是完全可以接受的:
interface A {
void foo() throws IOException;
}
interface B extends A {
void foo();
}
A a = new B() { ... }
try {
a.foo();
} catch (IOException e) {
// must catch even though B.foo() won't throw one
}
但是,您的 BookNotFoundException
可以扩展 RuntimeException
或 RemoteException
。但是不确定这是一个好方法。
关于Java接口(interface)扩展题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/616684/