覆盖 Kotlin 中的私有方法

时间:2021-06-19 09:02:43

标签: java android kotlin

我知道私有方法不能被覆盖,但这是我的问题。

A_CLASS_FROM_3RD_PARTY_LIBRARY_THAT_I_CANNOT_MODIFY 来自我无法修改的 3rd 方库:

open class A_CLASS_FROM_3RD_PARTY_LIBRARY_THAT_I_CANNOT_MODIFY {
    private fun print() {
        println("A")
    }
    
    open public fun run() {
        // A lot of code here
        // A lot of code here
        // A lot of code here
        
        print()
        
        // A lot of code here
        // A lot of code here
        // A lot of code here
    }
}

我唯一想改变的是其中的 print() 方法。有没有比覆盖整个 run() 方法并复制并粘贴超类中的所有代码以覆盖私有 print() 方法更好的方法?例如,

class B : A_CLASS_FROM_3RD_PARTIES_THAT_I_CANNOT_MODIFY() {
    private fun print() {
        println("B")
    }
    
    // Copy & paste the whole run() method from supper class
    override public fun run() {
        // A lot of code here
        // A lot of code here
        // A lot of code here
        
        print()
        
        // A lot of code here
        // A lot of code here
        // A lot of code here
    }
}

1 个答案:

答案 0 :(得分:3)

无论是在 Kotlin 中还是在 Java 中,都无法覆盖私有方法。