0

I have a class A -> class B (child of A) -> class C (child of B) and class A -> class D. How can I write a function that return objects from class B and class D, example below. How to implement the calling part?

The problem is If I do A a = getFunction() I cannot access the B's functions.

public <T> T getFunction(IntegrationType integrationType) {
      return (T) integrationFactory.createIntegration(integrationType);
}
7
  • 1
    What do you mean by "class A -> class D"? Are you saying class D is a child of A? Commented Aug 4, 2023 at 22:50
  • Maybe include more code in your example. Commented Aug 4, 2023 at 22:51
  • I may not understand what you're asking, but since A is the parent, you could do something like this: A classB = new B(); A classD = new D(); classB.getFunction(): classD.getFunction(); Commented Aug 4, 2023 at 22:52
  • @Mahesh Have a look at java Collections class - e.g Collections.<String>emptyList() - gives you a list where the return type is List<String>.. Commented Aug 4, 2023 at 22:52
  • Have you tried public <T extends A> getFunction... - so then the return type is exactly what you want ... Commented Aug 4, 2023 at 22:54

1 Answer 1

1

The problem is If I do A a = getFunction() I cannot access the B's functions.

You can use the instanceof operator. For example:

A a = getFunction();
if (a instanceof B) {
    B b = (B) a;
    // you can call the methods of B here
}

Or, if you are using Java 16 or higher, you can try the pattern matching as follows:

A a = getFunction();
if (a instanceof B b) {
    b.someMethod();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.