Here's an example:
abstract class Parent {
constructor() {
sayName()
}
abstract fun sayName()
}
class Child : Parent() {
private var name: String = "Melina"
override fun sayName() {
if (name == null) name = "John"
println(name)
}
}
fun main() {
println("Hello, world!!!")
var child = Child()
child.sayName()
}
Live: https://pl.kotl.in/vIuBzrBON
The problem: a sub class would like to override an abstract method and use a private var in that method. The subclass private var would normally be null
in the parent class constructor, so I added the line
if (name == null) name = "John"
in order to define the value in that case. However, the subclass will still override the value "John" with the value "Melina".
How can we prevent the subclass from overriding the value, so that it will remain "John"?
I know I could put "Melina" in both places, but I am wondering if it is possible to not repeat the value.