关于实现接口方法的困惑 [英] Confusion in regarding implementing interface methods

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

问题描述

HI
我有一个问题如果界面有四种方法,我想只实现两种方法,如何实现?

HI I have a question If interface has got four methods,and I like to implement only two methods, how this could be achieved?

可以任何解释是可能的,或者我应该去实现所有的方法。

Can any explain is that possible or should I go for implementing all the methods.

推荐答案

你不能部分实现一个接口没有声明实现类的抽象,因此要求某些子类提供剩余的实现。原因是接口是契约,实现它声明我提供接口指定的行为。其他一些代码将通过声明的接口使用你的类,并期望方法在那里。

You can't "partially" implement an interface without declaring the implementing class abstract, thereby requiring that some subclass provide the remaining implementation. The reason for this is that an interface is a contract, and implementing it declares "I provide the behavior specified by the interface". Some other code is going to use your class via the declared interface and will expect the methods to be there.

如果你知道用例不使用其他两种方法你可以通过抛出OperationNotSupported来实现它们。这是否有效取决于接口和用户。如果接口可以通过这种方式合法地部分实现,那么接口设计很差并且可能应该是两个接口的代码气味。

If you know the use case does not use the other two methods you can implement them by throwing OperationNotSupported. Whether this is valid or not very much depends on the interface and the user. If the interface can legitimately be partially implemented this way it would be a code smell that the interface is poorly designed and perhaps should have been two interfaces.

你也可以通过什么都不做来实现接口,尽管这通常只适用于监听器或回调实现。

You may also be able "implement" the interface by doing nothing, though this is usually only proper for "listener" or "callback" implementations.

简而言之,这完全取决于。

In short, it all depends.

这篇关于关于实现接口方法的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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