加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java接口扩展了问题

发布时间:2020-12-15 02:05:09 所属栏目:Java 来源:网络整理
导读:我必须实现一个RMI服务器,它将成为另外两个RMI服务的前端.因此,我认为合乎逻辑的做法是将此实现的接口用于其他两个服务的接口. public interface FrontEndServer extends Remote,BookServer,StudentServer{ // Block empty so far} 但是StudentServer上有一
我必须实现一个RMI服务器,它将成为另外两个RMI服务的前端.因此,我认为合乎逻辑的做法是将此实现的接口用于其他两个服务的接口.

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 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.但不确定这是一个好方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读