I have a question about access modifiers override.
First, let’s look at the following code.
fun main() {
val b: AAA = BBB()
b.testA()
}
open class AAA() {
fun testA() {
println("This is testA()")
}
}
open class BBB() : AAA()
result:
This is testA()
No problem with this code, b
has printed testA()
of class AAA.
Let’s see the following code.
fun main() {
val b: AAA = BBB()
b.testA()
}
open class AAA() {
open fun testA() {
println("This is testA()")
}
}
class BBB() : AAA() {
override fun testA() {
println("This is overrided testA() ")
}
}
result:
This is overridden testA()
This code is also no problem.
Now, here’s the code I’m going to ask.
fun main() {
val b: AAA = BBB()
b.testA()
}
open class AAA() {
protected open fun testA() {
println("This is testA()")
}
}
class BBB() : AAA() {
public override fun testA() {
println("This is overridden testA()")
}
}
This code will not be executed. The IDE complains Cannot access 'testA': it is protected in 'AAA'
.
Although testA()
of AAA
is protected
, it was overridden as public
in BBB
, so I thought that naturally the overridden testA()
of BBB
would be called like the second code.
What’s the problem?
Am I missing something?
What part of inheritance and access modifiers am I misunderstanding?