多态性与泛型?

huangapple go评论133阅读模式
英文:

Polymorphism with generics?

问题

我有一个类A -> 类B(A的子类) -> 类C(B的子类)和类A -> 类D。
如何编写一个函数,返回类B和类D的对象,示例如下。
如何实现调用部分?

问题在于,如果我执行 A a = getFunction(),我无法访问B的函数。

英文:

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

答案1

得分: 1

以下是翻译好的部分:

问题是,如果我执行 A a = getFunction(),我无法访问 B 的函数。

您可以使用 instanceof 运算符。例如:

A a = getFunction();
if (a instanceof B) {
    B b = (B) a;
    // 您可以在这里调用 B 的方法
}

或者,如果您正在使用 Java 16 或更高版本,您可以尝试以下模式匹配:

A a = getFunction();
if (a instanceof B b) {
    b.someMethod();
}
英文:

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

huangapple
  • 本文由 发表于 2023年8月5日 06:45:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定