-1

I have two classes, class A and class B, which each have a method with the same name. Is it possible to have one variable, maybe of type Object, that could be able to contain both types of classes and perform their methods?

As an example of what I mean:

class A {
    public void doSomething() {
        ...
    }
}

class B {
    public void doSomething() {
        ...
    }
}

class Test {
    Object obj;

    if (isTrue) 
        obj = new A();
    else
        obj = new B();

    obj.doSomething();
}

I looked into Reflection, but I am not sure if it can be used to do what I want or not.

Any help is cool, thanks.

0xCursor
  • 2,242
  • 4
  • 15
  • 33
  • 2
    If `A` and `B` were to both extend a superclass/implement an interface `C` that contains the `doSomething` method, then you can use `C c = new A()` or `C c = new B()`, and call `c.doSomething()`. – hnefatl Apr 13 '18 at 18:44

2 Answers2

3

The best thing you can do is create an interface and have both classes implement it. This way, you can have a single common type which you can assign these objects to and not have to do instance checks or casting.

public interface C {
    void doSomething();
}

public class A implements C {
    @Override
    public void doSomething() {
    }
}

public class B implements C {
    @Override
    public void doSomething() {
    }
}

public class Test {
    public C obj;

    obj = new A(); // or new B()

    obj.doSomething();
}
killjoy
  • 3,665
  • 1
  • 19
  • 16
  • Thanks, I believe this is the solution. I will try it out and see if it is what I am looking for. – 0xCursor Apr 13 '18 at 18:55
  • 1
    Just a note about the @Override annotation. It's not strictly required, but it does help to ensure your code isn't broken. If you accidentally spell the method wrong or put it on a method not defined in the interface (or any super type), the compiler will catch it and error. – killjoy Apr 13 '18 at 19:04
1

Java Polymorphism is the key. Make your classes implement an interface defining your method:

interface DoSomethingable {
  void doSomething();
} 
class A implements DoSomethingable {
public void doSomething() {
    ...
  }
}
class B implements DoSomethingable {
public void doSomething() {
    ...
  }
}
class Test {
  public static void main(String... args) {
    DoSomethingable obj;

    if (isTrue) {
      obj = new A();
    } else {
      obj = new B();
    }

    obj.doSomething();
  } 
}
Gonzalo Matheu
  • 8,984
  • 5
  • 35
  • 58