Consider the following:
scala> :paste
// Entering paste mode (ctrl-D to finish)
object O {
protected case class I(x: Int)
trait T {
protected def m: I = I(0)
}
}
val i = new O.T { override def m = super.m }.m
// Exiting paste mode, now interpreting.
defined object O
i: O.I = I(0)
scala> :type i
O.I
If I add : O.I after val i this code snippet fails to compile, but statement i.x compiles and returns 0 in runtime.
Is it a compiler bug or there is a good reason for such behavior?
Derived classes can in any case brake protection as they have full access to base class protected members. Consider public method foo below
val i = new O.T {
override protected def m = super.m
def foo = m
}
We keep m as protected, nevertheless i.foo indirectly "brakes out" of protection and evaluates to res0: O.I = I(0). So it seems we do not gain much by preventing widening on overriding.
Also consider related answer to When overriding a method, why can I increase access but not decrease it?:
It's a fundamental principle in OOP: the child class is a fully-fledged instance of the parent class, and must therefore present at least the same interface as the parent class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With