Nirmal
Nirmal

Reputation: 43

How to invoke 2 different methods of 2 different classes to my own class in java?

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.

Upvotes: 1

Views: 1850

Answers (2)

iavanish
iavanish

Reputation: 509

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();

Upvotes: 1

Yussef
Yussef

Reputation: 610

Maybe I will do this,

class A{
  public void m1{};
}

class B{
  public void m2{};
}

class OneOverrideA extends A{
    @Override
    public void m1{};
}

class OneOverrideB extends B{
    @Override
    public void m2{};
}

class FatherClass extends OneOverrideA{

  //well you have your class method m1 here but we cannot extend more than two class

  public void m2{new OneOverrideB().m2()};

}

Although it is not awesome in my point of view, anyway why would you want to override both methods? if you're going to do that why not create them from zero? or are you going to use other methods from those class? nvm I would use composition anyway.

Hope it can re fresh your mind and get something from here :) GL

Upvotes: 0

Related Questions