0

例如我有这个代码:

abstract class A {
  def functionA() {
    val a : A = null; // take null just for temporary, because I cannot think what should to put here
    a.functionB
  }

  def functionB() {
      print("hello")
  }
}

class C extends A{
}

object Main extends App {
  val c : C = new C()
  c.functionB // print hello
  c.functionA // ERROR
}

functionA,我想声明一个对象以防万一:如果当前类是 C,a 将具有 C 类型。如果当前类是 D,a 将具有 D 类型。因为我不能这样做:

val a : A = new A // because A is abstract

在 Java 中,我可以轻松地做到这一点,但在 Scala 中我不能这样做。请帮帮我。

谢谢 :)

4

1 回答 1

1

我想声明一个对象以防万一:如果当前类是 C,a 将具有 C 类型。如果当前类是 D,a 将具有 D 类型

如果我理解正确,您说的是简单的继承多态性。您可以在您的案例中分配对value 的this引用,或者直接使用它:a

abstract class A {
  def functionA {
    this.functionB
  }

  def functionB {
    print("hello")
  }
}

class C extends A{
}

object Main extends App {
  val c : C = new C()
  c.functionB
  c.functionA
}

在这种情况下,将没有NullPointerException.

但是,如果您真的想在基类中创建真实类型的对象,则应该以其他方式使用继承多态性(我认为这比@brunoconde 建议的要简单一些,但想法非常相似;我不认为这里真的需要泛型):

abstract class A {
  def functionA {
    val a : A = create()
    a.functionB
  }

  def functionB {
    print("hello")
  }

  def create(): A
}

class C extends A {
  override def create() = new C
}

如果必须,这就是我在 Java 中所做的。但是,您必须create()在每个子类中覆盖方法。我怀疑是否有可能在不诉诸反思的情况下不覆盖而做到这一点。

于 2012-10-10T12:48:20.767 回答