Java接口(interface)扩展题

标签 java interface

我必须实现一个 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 可以扩展 RuntimeExceptionRemoteException。但是不确定这是一个好方法。

关于Java接口(interface)扩展题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/616684/

相关文章:

java - 无法从通知中打开 Activity

.net - 如何在.net的程序集中查找特定接口(interface)的所有类

class - TypeScript 类和同名接口(interface)之间的关系

java - 使用 Neo4j 和 Mysql 构建社交网站

java - Java 中的新功能 Lambda 重载

java - HttpAsyncClient 4 如何工作?

java - 如何使用java中的反射查找类中使用其他接口(interface)扩展其他类的所有接口(interface)

javascript - 防止覆盖提供的内部函数的方法

c# - Autofac:使用非泛型接口(interface)注册泛型类型

java - hibernate 更新不起作用