case 1: override var i to change visibility
It only works when both Test1.i
and Test1Scala.i
are val
, otherwise resulta in a compile error: "variable i cannot override a mutable variable".
package test
class Base1 {
private[test] var i = 0
}
class Child1Scala extends Base1 {
override var i = 1
}
This limitation can be bypassed by using java
class Child1Java extends Base1 {
@Override public int i() {
return super.i();
}
@Override public void i_$eq(int value) {
super.i_$eq(value);
}
}
case 2: override var i to add some code for logging
Doesn't work at all, neither var
nor val
. It always results in a compile error: "super may not be used on variable i". But without super
, there methods will become infinite tail call
class Base2 {
var i = 0
}
class Child2Scala extends Base2 {
override def i: Int = {
println("get")
super.i
}
override def i_=(value: Int): Unit = {
println("set")
super.i = value
}
}
Again, it's legal in java
class Child2Java extends Base2 {
@Override public int i() {
System.out.println("get i");
return super.i();
}
@Override public void i_$eq(int value) {
System.out.println("set i");
super.i_$eq(value);
}
}