问题
I have two classes that need to extend one class. I am getting a compiler error since this cannot happen in Java. I know that you can implement as many interfaces you want to in Java but can only extend one other class. How can I fix this problem?
回答1:
Use a "has A" relationship instead of "is An".
class A
class B
You (think) you want:
class C extends A, B
Instead, do this:
class C {
A theA;
B theB;
}
Multiple inheritance is almost always abused. It's not proper to extend classes just as an easy way to import their data and methods. If you extend a class, it should truly be an "is An" relationship.
For example, suppose you had classes,
class Bank extends Financial
class Calculator
You might do this if you want to use the functions of the Calculator
in Bank
,
class Bank extends Calculator, Financial
However, a Bank
is most definitely NOT a Calculator
. A Bank uses a Calculator
, but it isn't one itself. Of course, in java, you cannot do that anyway, but there are other languages where you can.
If you don't buy any of that, and if you REALLY wanted the functions of Calculator
to be part of Bank
's interface, you can do that through Java interfaces.
interface CalculatorIntf {
int add(int a, int b);
}
class Calculator implements CalculatorInf {
int add(int a, int b) { return a + b };
}
class Bank extends Financial implements CalculatorIntf
Calculator c = new Calculator();
@Override // Method from Calculator interface
int add(int a, int b) { c.add(a, b); }
}
A class can implement as many interfaces as it wants. Note that this is still technically a "has A" relationship
回答2:
"Two classes that extend one class" is legal.
"One class extending two classes" is against the specification of the language. If you do not want to consider interfaces, it cannot be done.
回答3:
Two classes extending ONE class? like so:
class A{ }
class B extends A{ }
class C extends A{ }
Here, B and C(two classes) extend A(one class). But I am sure you meant One class extending Two separate classes(Multiple Inheritance). WorkAround: you could make a composite Object that has two separate objects(Has-A relationship) like so:
class A { }
class B { }
class C extends A { /*define new functionality here */ }
class D extends B { /*define new functionality here */ }
class E { private C cObj; private D dObj; }
回答4:
To avoid diamond problem Java does not support Multiple Inheritance through classes but it supports using interfaces.
So you may use Association
Relationship. e.g.
Class A {}
Class B {}
Class C implements SomeInterface {
A a;
B b;
// setter getter for a and b and other methods
}
来源:https://stackoverflow.com/questions/12518972/since-a-class-in-java-cannot-extend-multiple-classes-how-would-i-be-able-to-get