Java,无法降低对象继承方法的可见性 [英] Java, Cannot reduce the visibility of the inherited method from object
问题描述
继续这个问题:为什么你不能在一个 Java 子类?
我需要创建与 A
类几乎相同的 B
类,除了 B
不能做 A 的某些事情
可以.
I need to create class B
that is almost identical to class A
, except that B
cannot do certain things that A
can.
作为一个懒惰的程序员,我试图继承A
,却发现B
不能降低A
方法.呃!...
Being a lazy programmer as I am, I tried to inherit A
, only to greet with error that B
cannot reduce the visibility of A
methods. Duh!..
现在A
是一个厂商的API,我的目的是封装这个API,方便使用.
Now A
is an API from a vendor, my intention is to encapsulate this API so that it is easier to use.
我想知道解决此问题的最佳做法是什么?
I wonder what is the best practice to work around this?
推荐答案
两个选项:
如果需要 B
保持与 A
相同的接口(以便客户端代码可以使用两者中的任何一个而无需更改),则可以覆盖禁止"方法在 B
中并让它们抛出 UnsupportedOperationException
.例如:
If you need B
to keep the same interface as A
(so that client code can use any of the two without changes), you can override "forbidden" methods in B
and have them throw an UnsupportedOperationException
. For example:
public class A
{
public int allowedMethod() { ... }
public int forbiddenMethod() { ... }
}
public class B extends A
{
public int forbiddenMethod()
{
throw new UnsupportedOperationException("Sorry, not allowed.");
}
}
或者,如果您真的希望 B
的 API 成为 A
API 的子集,那么只需让 B
包含一个A
的实例,并适当地委托方法调用.
Or, if you really want the API of B
to be a subset of the API of A
, then just have B
contain an instance of A
, and delegate method calls appropriately.
public class A
{
public int allowedMethod() { ... }
public int forbiddenMethod() { ... }
}
public class B
{
private A a;
public int allowedMethod()
{
return a.allowedMethod();
}
}
这篇关于Java,无法降低对象继承方法的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!