限制可以在Java中实现接口的类 [英] Restrict classes that can implement interface in Java

查看:62
本文介绍了限制可以在Java中实现接口的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开始之前:我知道这个问题而在我的情况下,该答案将无效.

Before we start: I'm aware of this question and in my case that answer will not work.

所以说我有:

interface Iface
class SuperClass (this one is from external library and can't be changed)
class SubClass extends SuperClass
class OtherClass

有没有一种方法可以使Iface只能由SuperClass及其子类实现?因此,在这种情况下:

Is there a way to make it so that Iface can only be implemented by SuperClass and its subclasses? So in this case:

class SuperClass implements Iface - would be good if I could edit that class
class SubClass implements Iface   - good
class OtherClass implements Iface - bad

另一个问题:这样做是违反OOP原则还是恶意代码的征兆?

Side question: is that against OOP principles or is it a sign of bad code to do so?

推荐答案

我看到的唯一选择是将接口设置为包私有,并由位于同一包中的公共SuperClass实施该接口.这样,程序包的用户将可以继承SuperClass的子类,但不能直接实现您的接口.请注意,尽管如此,界面本身并不是很有用,因为外面的人都看不到它.

The only option I see is to make the interface package-private and implement it by public SuperClass which is located in the same package. This way the users of your package will be able to subclass the SuperClass, but not able to implement your interface directly. Note though that this way the interface itself becomes not very useful as nobody outside can even see it.

通常看来,只需删除接口并将其替换为SuperClass即可解决您的问题.

In general it seems that your problem can be solved just by removing the interface and replacing it everywhere with SuperClass.

这篇关于限制可以在Java中实现接口的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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