abstract class A {
abstract string foo();
}
class B extends A {
string foo () { return "bar"; }
}
class C extends A {
string foo() {return "baz"; }
}
class D extends B, C {
string foo() { return super.foo(); } //What do I do? Which method should I call?
}
C + + 和其他语言有一些方法来解决这个问题,例如
string foo() { return B::foo(); }
但 Java 只使用接口。
Java Trails 对接口有很好的介绍: < a href = “ http://download.oracle.com/javase/lessons/Java/views/interface.html”rel = “ noReferrer”> http://download.oracle.com/javase/tutorial/Java/concepts/interface.html
在深入研究 Android API 的细微差别之前,您可能需要遵循这一点。
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();
}
}
public interface FooInterface {
public void methodA();
public int methodB();
//...
}
public interface BarInterface {
public int methodC(int i);
//...
}
现在让 Foo和 Bar实现相关的接口:
public class Foo implements FooInterface { /*...*/ }
public class Bar implements BarInterface { /*...*/ }
现在,使用 class FooBar,您可以同时实现 FooInterface和 BarInterface,同时保留一个 Foo和 Bar对象,并直接传递方法:
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);
}
//...
}
public abstract class FatherClass {
abstract void methodInherit() {
//... do something
}
}
public interface InterfaceWithDefaultsMethods {
default void anotherMethod() {
//... do something
//... maybe a method with a callable for call another function.
}
}
因此,在此之后,您可以扩展和实现这两个类和
使用这两种方法。
public class extends FatherClass implements InterfaceWithDefaultsMethods {
void methode() {
methodInherit();
anotherMethod();
}
}