有没有办法使扩展多态?

问题描述 投票:0回答:1

我有以下无法更改的 java 类

interface Parent...
class Child1Class implements Parent...
class Child2Class implements Parent...
class GrandChild1Class extends Child1Class ...
...

现在我编写 Kotlin 应用程序。

我想向所有层次结构添加一些功能。

fun Parent.foo(){ println("Parent.foo")

但是我想要有特殊的行为

GrandChild1Class

fun Parent.foo(){ println("GrandChild1Class.foo")

但是如果我写:

val grandChild1: Parent = GrandChild1Class()
grandChild1.foo()

我看到

Parent.foo
因为参考类型

但我希望看到

GrandChild1Class.foo

有没有办法实现这种事情的多态行为?

java kotlin inheritance polymorphism extension-methods
1个回答
0
投票

您对多态性的思考方向是错误的。 子类型需要具有特殊行为。

© www.soinside.com 2019 - 2024. All rights reserved.