Hello imagine that we have following class
Manager{
public static void doSth(){
// some logic
};
}
How to override that method in k
Short Answer
No
"Short" Explanation
You can only override virtual methods and also you can shadow/replace static methods in Java, but you can't shadow a "static" method in Kotlin as the static method will not be available using the child class qualifier already. And even when using extension methods, you simply can't do it for either static or non-static as the member function will always win(see the example below). What you can do is to subclass the parent and add a new companion object that has a method with the same name as the parent and call the parent method from inside.
Full Explanation
companion object
which behaves similarly and you can access the method
of the companion object as if it were a java static method using only
the class name as a qualifier but you can't access the methods of
companion object of a parent class from its child like Java.open class A {
fun foo() {
println("A.foo()")
}
companion object {
fun bar() {
println("A.Companion.bar()")
}
}
}
class B: A()
fun A.foo() {
println("A.foo() extension")
}
fun A.Companion.bar() {
println("A.Companion.bar() extension")
}
fun A.Companion.baz() {
println("A.Companion.baz() extension")
}
fun main(args: Array<String>) {
A().foo() // prints A.foo()
A.bar() // prints A.Companion.bar()
A.baz() // prints A.Companion.baz() extension
B.bar() // COMPILE ERROR
}
You can't do that in Kotlin. The problem is that there is no static
keyword in Kotlin. There is a similar concept (companion object
) but the problem is that your original Java class doesn't have one.
static
methods don't support inheritance either so you can't help this on the Java side.
If you want to declare extension methods which are "static" (eg: put them on a companion object
) you can do this:
class Manager {
companion object
}
fun Manager.Companion.doSth() = println("sth")
Then you can call it like this:
Manager.doSth()
Note that you can only augment Kotlin classes this way which have a companion object
.