【问题标题】:Inherited class that changes all inherited public methods to private将所有继承的公共方法更改为私有的继承类
【发布时间】:2014-11-24 02:02:33
【问题描述】:

我想为 android 创建自己的 UI 小部件类,它是 LinearLayout 的继承类。

public class MyOwnClass extends LinearLayout {

    ...
    public void setSomeProperties(Object properties) { ... }

但是 LinearLayout 有很多公共方法,我想要在我的类中定义的唯一公共方法。如何让 MyOwnClass 的实例无法访问 LinearLayout 的所有公共方法?

myOwnClass.setSomeProperties(properties); // only this should be accesible
myOwnClass.setBackground(...); // this should'nt be accesible

【问题讨论】:

  • 但是方法太多了..我不想把它们都放在我的课上
  • “但是 LinearLayout 有很多公共方法,我想要我在我的类中定义的唯一公共方法”——你别无选择,只能拥有“很多公共方法”,如这些在View 上定义为公开的,您需要从View 继承来创建您自己的“UI 小部件类”。例如,setBackground() is defined on View as being public,因此您无法将其设为 public 以外的任何内容。
  • 这很令人沮丧

标签: java android class inheritance private


【解决方案1】:

你应该使用组合而不是继承。

您可以通过在 MyOwnClass 中包装 LinearLayout 的实例而不是从它继承来做到这一点。然后你可以选择哪些方法是公开的。

public class MyOwnClass {
    LinearLayout layout;

    public MyOwnClass ()
    {
        layout = new LinearLayout ();
    }

    // do the following only for methods of LinearLayout you wish to stay public in
    // new class 
    public SomeReturnValue someMethod (... someParams ...)
    {
        return layout.someMethod (... someParams ...)
    }
}

这样,您可以完全控制新类中包含的 LinearLayout 的哪些公共方法仍可供新类的用户访问。

【讨论】:

  • 换行到底是什么意思?我是否只需要在我的类中创建一个 LinearLayout 实例并将其存储为我类的一个字段?
  • @Incredible 是的,就是这个意思,如我的代码示例所示。
  • @Eran:总的来说,您的回答是正确的,因此我赞成。在问题的特定情况下,大多数public 方法实际上是在基类(View)上定义的,OP 的类也需要扩展为 OP 自己的“UI 小部件类”。因此,在实践中,在这种情况下,这将导致大量代码和非常少的额外可见性控制。
  • 但是当其他程序员使用我的类时,LinearLayout 怎么会在活动中膨胀?如果 MyOwnClass 是 LinearLayout 本身很容易膨胀那个视图,但是如果 LinearLayout 被包裹在新的类中呢?
猜你喜欢
  • 2011-01-05
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 2015-03-07
  • 2011-08-10
  • 1970-01-01
相关资源
最近更新 更多