有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java重写Kotlin中的私有方法

我知道私有方法不能被重写,但我的问题是

A_CLASS_FROM_3RD_PARTY_LIBRARY_THAT_I_CANNOT_MODIFY来自第三方库,我无法修改:

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()方法并复制&;粘贴Super类中的所有代码,以便重写private 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) 个答案

  1. # 1 楼答案

    在Kotlin和Java中都不可能重写私有方法