I have a requirement to invoke two different methods from two different classes to my own class and those two classes are in two different .jar files provided by the vendors.
The scenario is something like below:
My own class is MyClass{}. If I have to use those two methods in my class I need to extend both the classes, but since java does't support multiple Inheritance, I am not able to achieve it.
Please share if there is any other way to access both m1() & m2() methods in my class. Note: I have to extend the available functionalities and should customize the methods according to my requirement.
Edit: The question was clarified later, the OP wants to extend the functionalities of the classes.
One idea would be to create two separate sub-classes for the two different base classes. Extend the functionalities in these sub-classes and then use composition in your MyClass to use the functionalities of these sub-classes and their super-classes.
public class SubA extends A {
@Override
public void m1() {
// add extra functionalities
super.m1(); // invoke existing functionalities
}
}
public class SubB extends B {
@Override
public void m2() {
// add extra functionalities
super.m2(); // invoke existing functionalities
}
}
public class MyClass {
SubA a = new SubA();
SubB b = new SubB();
a.m1();
b.m2();
}
You can also refer to this question How do Java Interfaces simulate multiple inheritance? for detailed explanation of how to implement multiple-inheritance in Java.
Earlier answer:
Both the methods are public, so you don't need to extend the classes to use those methods. Just create an object of those two classes and call their respective methods.
A a = new A();
a.m1();
B b = new B();
b.m2();