Scala中不能简单调用父类构造器引起的问题


我现在有一个别人写的带构造方法的父类ParentClass,其中有一个public的成员变量attr和一个利用attr来做一些事情的方法somethingWithAttr。用Scala语言表达一下大概是这样:


 class ParentClass(var attr:Int) {
  def somethingWithAttr = attr * 2
}

这个类我是不能动的。

此时我要扩展这个类,加一个利用attr做其他事情的方法。我的代码如下:


 class SonClass(attr:Int) extends ParentClass(attr) {
  def anotherThingWithAttr = super.attr * 3
}

然后我测试了一下


 val obj = new SonClass(2)
obj.attr = 4
println(obj.somethingWithAttr) // => 8
println(obj.anotherThingWithAttr) // => 6

因为在子类构造器的attr参数被类体使用,从而在子类中也生成了一个同名的attr属性覆盖了父类的attr。而 attr_= 是父类因为 var attr:Int 声明自动生成的方法,操作的是父类的attr属性。在子类又不能使用super.attr来强制取父类的attr属性,导致了父类的attr在子类中无法访问的问题。

我用了一个不成熟解决方案就是在子类的构造器中将attr改名:


 class SonClass(anotherAttr:Int) extends ParentClass(anotherAttr) ...

但是这样也浪费了一点空间来存储没有用的 anotherAttr 属性,解决的并不完美。

写成trait混入一个doAnotherThingAttr也可以解决,但是这样在用我这个库来构造对象的时候就必须要用类似 new ParentClass with AnotherThing 的长长的写法,只要写成类,就会牵扯到构造器的问题。

请教一下有没有完美的解决方案

scala 继承

蛋包饭茶水卫门 10 years, 9 months ago

但是这样也浪费了一点空间来存储没有用的anotherAttr属性,解决的并不完美。

常规的想: 就算你在 SonClass 中使用 attr ,也是浪费了空间。子类一个 attr, 父类也是一个 attr,和你使用 anotherAttr 并没有本质区别。

事实上: 如果你的 anotherAttr 并没有在子类中使用到。那么就仅仅是一个父类型传参数而已。所以,使用 anotherAttr ,反而还节约了空间。因为这个字段可以没有。

详见 javap 反编译: 这是 含有 attr 的 SonClass 反编译结果:


 public class learn.SonClass extends learn.ParentClass {
  private final int attr;
  public int anotherThingWithAttr();
  public learn.SonClass(int);
}

会有 attr 这个字段。因为 anotherThingWithAttr 方法中使用了这个字段。所以 scala 编译器会在子类中新增这个字段。

再来看下使用 anotherAttr 反编译结果:


 public class learn.SonClass extends learn.ParentClass {
  public int anotherThingWithAttr();
  public learn.SonClass(int);
}

反而还少用了一个字段。因为你的子类并没有使用anotherAttr,仅仅是用来做构造器的传参而已。

所以楼主,你的方案是好方案。Cheers!

泰坦的回憶 answered 10 years, 9 months ago

Your Answer