简体   繁体   中英

What happens when a constructor of an abstract class is private in kotlin?

I don't understand what happens when a constructor of an abstract class is private in Kotlin. In this example I am using a sealed class and it has a private constructor by default. However, I am able to call the private constructor from subclasses.

sealed class Operation(val x: Int, val y: Int)
class Add(x: Int, y: Int) : Operation(x, y)
class Subtract(x: Int, y: Int) : Operation(x, y)
class Multiply(x: Int, y: Int) : Operation(x, y)
class Divide(x: Int, y: Int) : Operation(x, y)

Private constructors are not allowed to be called when you want to instantiate the class using the constructor. However, if the class is abstract it doesn't matter if the constructor is private or public because the class cannot be instantiated.

Could you clarify me what does imply having a private constructor on an abstract class?

For non- sealed abstract class, a private constructor can only be called by other constructors, or by nested subclasses, as in

open class Operation private constructor (val x: Int, val y: Int) {
    class Add(x: Int, y: Int) : Operation(x, y)
}

And before Kotlin 1.1, all subclasses of a sealed class had to be nested, and so could call the private constructor.

I guess that part of documentation simply wasn't adjusted after the change, now it would make more sense to call the constructor of a sealed class protected instead of private.

Note that

open class Operation private constructor (val x: Int, val y: Int)
class Add(x: Int, y: Int) : Operation(x, y)

does not compile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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