Java中,不能减少的对象继承方法的可见性 [英] Java, Cannot reduce the visibility of the inherited method from object

查看:1165
本文介绍了Java中,不能减少的对象继承方法的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从这个问题继续:<一href=\"http://stackoverflow.com/questions/1600667/method-overriding-and-visibility-in-java\">http://stackoverflow.com/questions/1600667/method-overriding-and-visibility-in-java

我需要创建类 B 几乎相同类 A ,但不能做某些事情, 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 (以便客户端code可以使用任何两个没有改变),你可以覆盖 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屋!

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