I work with a specific API library in Java. It has a base class A, as well as B and C, which extend the capabilities of A. B and C, provide similar, but excellent functionality, all three classes are in the library.
public abstract class A { virtual foo(); } public class B extends A {} public class C extends A {}
How do I get items A, Band Cin my class? If I use interfaces to implement classes, there are a lot of duplicate code, and inner classes do not allow me to override existing methods, so that the calling interface A, Band Cstored.
A
B
C
How to implement multiple inheritance in Java?
EDIT: Thanks for editing George, now he is clearer, forgot to mention one critical requirement: my classes must have A as a base so that they can be controlled by the platform API.
Recall that you have:
class A { public void foo() {} } class B extends A { public specificAMethod() {} } class C extends A { public specificCMethod() {} }
The above classes are in a library that you cannot access or modify. You want the behavior of B and C in the third class D, as if you could write:
class D extends B, C { }
Right?
How about using B and C instead of inheritance? Do you really need inheritance? Do you want to call private methods B and C?
class D { private B b; private C c; }
" ", , "Inherited" . "-"? "Has-a" , , , , .
, , 3 - 3, - , - 3, ( ). , , , .
- - , . , Java- , , (, , , , ! mixin ).
, A - D - foo(), E F, D .
. IDE .
Java , . , .
COM : IUnknown, , Java :
Object queryInterface(Class<?> clazz)
:
if(clazz.isAssignableFrom(this.getClass())) return this; else return null;
, , :
else if(class == SomeClass.class) { return something; } else ...
, , , , "" , ++, , . p >
Java 1.8 . , . . fiew (. ), .
public interface A { default A foo() { return this; } } public interface B extends A { @Override default B foo() { return this; } } public interface C extends A { @Override default C foo() { return this; } } public interface D extends B, C { @Override // if the return type does not implement B and C // the comiler will throw an error here default D foo() { return this; } }
Note that this is, but note that you cannot call super.fooor define fields or private members (before Java 9) since they still don't work. If you accept these limitations, this will open up a new level of object-oriented programming.
super.foo