从两个类扩展

2022-08-31 06:32:46

我该怎么做:

public class Main extends ListActivity , ControlMenu 

另外,我想知道这种方法是可以的,我已经在课堂上制作了菜单,这是ControlMenu,我正在扩展其余的活动。


答案 1

只能扩展单个类。并从许多来源实现接口。

扩展多个类不可用。我能想到的唯一解决方案是不继承任何一个类,而是拥有每个类的内部变量,并通过将对对象的请求重定向到您希望它们转到的对象来执行更多的代理。

 public class CustomActivity extends Activity {

     private AnotherClass mClass;

     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         mClass = new AnotherClass(this);
     }

     //Implement each method you want to use.
     public String getInfoFromOtherClass()
     {
        return mClass.getInfoFromOtherClass();
     }
 }

这是我想到的最好的解决方案。您可以从两个类中获取功能,并且仍然实际上只有一种类类型。

缺点是无法使用强制转换来适应内部类的模具。


答案 2

正如其他人所说。不能。然而,尽管多年来人们已经多次说过你应该使用多个接口,但他们并没有真正研究如何。希望这会有所帮助。

假设你有,并且你们都想尝试扩展到.当然,正如你所说,你不能这样做:class Fooclass Barclass FooBar

public class FooBar extends Foo, Bar

人们已经在某种程度上了解了造成这种情况的原因。相反,为两者编写并涵盖其所有公共方法。例如:interfacesFooBar

public interface FooInterface {

    public void methodA();

    public int methodB();

    //...
} 

public interface BarInterface {

    public int methodC(int i);

    //...
}

现在制作并实现相关接口:FooBar

public class Foo implements FooInterface { /*...*/ }

public class Bar implements BarInterface { /*...*/ }

现在,使用 ,您可以同时实现和,同时保留 和 对象并直接传递方法:class FooBarFooInterfaceBarInterfaceFooBar

public class FooBar implements FooInterface, BarInterface {

    Foo myFoo;
    Bar myBar;

    // You can have the FooBar constructor require the arguments for both
    //  the Foo and the Bar constructors
    public FooBar(int x, int y, int z){
        myFoo = new Foo(x);
        myBar = new Bar(y, z);
    }

    // Or have the Foo and Bar objects passed right in
    public FooBar(Foo newFoo, Bar newBar){
        myFoo = newFoo;
        myBar = newBar;
    }

    public void methodA(){
        myFoo.methodA();
    }

    public int methodB(){
        return myFoo.methodB();
    }

    public int methodC(int i){
        return myBar.methodC(i);
    }

    //...

}

此方法的好处是,该对象适合 和 的模具。这意味着这完全没问题:FooBarFooInterfaceBarInterface

FooInterface testFoo;
testFoo = new FooBar(a, b, c);
testFoo = new Foo(a);

BarInterface testBar;
testBar = new FooBar(a, b, c);
testBar = new Bar(b, c);

希望这能澄清如何使用接口而不是多个扩展。即使我迟到了几年。


推荐