简体   繁体   English

当基础 class 已经导致 Kotlin 中的初始化时,如何防止子类私有 var 初始化?

[英]How to prevent subclass private var initialization when base class already caused the initialization in Kotlin?

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直播: 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.问题:子 class 想要覆盖抽象方法并在该方法中使用私有 var。 The subclass private var would normally be null in the parent class constructor, so I added the line子类私有 var 通常是null在父 class 构造函数中,所以我添加了这一行

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".但是,子类仍将使用值“Melina”覆盖值“John”。

How can we prevent the subclass from overriding the value, so that it will remain "John"?我们如何防止子类覆盖该值,使其保持为“John”?

I know I could put "Melina" in both places, but I am wondering if it is possible to not repeat the value.我知道我可以将“Melina”放在这两个地方,但我想知道是否可以不重复该值。

Better not to call actions in the constructor.最好不要在构造函数中调用操作。

Constructor is good place for initialize fields.构造函数是初始化字段的好地方。 If every child of Parent class should have name, you can declare it as field and set concrete value in child class.如果父 class 的每个子级都应该有名称,则可以将其声明为字段并在子级 class 中设置具体值。 So call sayName() method after construction of object:所以在构建 object 之后调用sayName()方法:

abstract class Parent {
    abstract val name: String
    
    abstract fun sayName()
}

class Child : Parent() {
    override val name: String = "Melina"
    
    override fun sayName() {
        println(name)
    }
}

If you use some framework for object creation, you can annotate your method with command to call this method after creation.如果您使用一些框架来创建 object,您可以使用命令注释您的方法以在创建后调用此方法。 For example, put @PostConstruct on method sayName() if you use Spring Framework.例如,如果您使用 Spring 框架,请将@PostConstruct放在方法sayName()上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM