code |
In this thread
http://thread.gmane.org/gmane.comp.lang.scala/4918
with this code
class Base(var base : int)
{
def getBase() = {
System.out.println("Base.getBase " + base)
base
}
}
class Derived1(base : int) extends Base(200)
{
override def getBase() = {
val s = this.base
System.out.println("Derived1.getBase " + s)
s
}
}
class Derived2(base : int) extends Base(200)
{
override def getBase() = {
val s = this.asInstanceOf[Base].base
System.out.println("Derived2.getBase " + s)
s
}
}
class Derived3(base : int) extends Base(200)
{
override def getBase() = {
val s = this.asInstanceOf[Derived3].base
System.out.println("Derived3.getBase " + s)
s
}
}
object Test extends Application
{
new Base(100).getBase()
new Derived1(100).getBase()
new Derived2(100).getBase()
new Derived3(100).getBase()
}
Martin Odersky states that
http://thread.gmane.org/gmane.comp.lang.scala/4918/focus=4921
"The reason it does not do this is the following: base in Derived1 is a
private field. As such it does not override the base field in class
Base. Instead, we have a case of shadowing. So if the static type of
the receiver is Derived1, you get its field, but if the static type is
Base, you get the hidden field. Java is not different there, I
believe."
This suggests that the output for Derived3 is incorrect, since
this.asInstanceOf[Derived3] is statically a Derived3, but it's
returning the base class field.
http://thread.gmane.org/gmane.comp.lang.scala/4918/focus=4922
Regards,
Blair
|