Java接口扩展了问题 [英] Java interface extends questions

查看:114
本文介绍了Java接口扩展了问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须实现一个RMI服务器,它将成为另外两个RMI服务的前端。所以我认为合乎逻辑的做法是将此实现的接口用于其他两个服务的接口。

I have to implement an RMI server which will be a front end for two other RMI services. So I decided a logical thing to do would be to have the interface for this implement the interfaces for the other two services.

public interface FrontEndServer extends Remote, BookServer, StudentServer
{
    // Block empty so far
}

然而,StudentServer上有一个方法

However there is a method on the 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 也要扔a BookNotFoundException 因为此服务还会在尝试添加详细信息之前验证图书是否实际存在。

I would like the FrontEndServer to also throw a BookNotFoundException as this service will also validate if the book actually exists before attempting to add the details in.

是这可能还是我的设计理念完全关闭,这实际上是一个糟糕的设计理念,好像其他接口改变了一样?我会更好地为 FrontEndServer 中的所有方法编写方法签名吗?

Is this possible or is my design idea completely off and this is actually a bad design idea as if the other interfaces change and all? And will I be better of writing the method signatures for all the methods inside the FrontEndServer?

推荐答案

如果扩展接口(如果实现接口,则同样适用),您不能覆盖方法并使其抛出更多检查的异常而不是原始方法。你可以扔掉相同或更少但不多。

If you extend an interface (the same applies if you implement an interface), you can't override a method and have it throw more checked exceptions than the original. You can it throw the same or less but not more.

想一想:

interface A {
  void foo();
}

interface B extends A {
  void foo() throws IOException;
}

A a = new B() { ... }
a.foo();

可能会抛出IOException但你无法知道。这就是为什么你不能这样做。

would potentially throw an IOException but you'd have no way of knowing. That's why you can't do it.

这当然是完全可以接受的:

This of course is perfectly acceptable:

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

Your BookNotFoundException could however extend RuntimeException or RemoteException. Not sure that's a good approach however.

这篇关于Java接口扩展了问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆