继承的类,将所有继承的公共方法更改为private

Inc*_*ble 0 java inheritance android private class

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

public class MyOwnClass extends LinearLayout {

    ...
    public void setSomeProperties(Object properties) { ... }
Run Code Online (Sandbox Code Playgroud)

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

myOwnClass.setSomeProperties(properties); // only this should be accesible
myOwnClass.setBackground(...); // this should'nt be accesible
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 5

您应该使用组合而不是继承.

你可以通过LinearLayout在你的内容中包含一个isntance来MyOwnClass代替继承它.然后您可以选择哪些方法是公开的.

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 ...)
    }
}
Run Code Online (Sandbox Code Playgroud)

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