【问题标题】:Scala : take abtract class as an object and can change when declare in normal classScala:以抽象类为对象,在普通类中声明时可以更改
【发布时间】:2012-10-10 10:55:12
【问题描述】:

例如我有这个代码:

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 中我不能这样做。请帮帮我。

谢谢:)

【问题讨论】:

  • 你将如何在 Java 中做到这一点?
  • 这是您采用的一些复杂的逻辑。重新考虑设计的确定信号。

标签: scala inheritance abstract-class


【解决方案1】:

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

如果我理解正确,您说的是简单的继承多态性。您可以在您的情况下将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

但是,如果您真的想在基类中创建真实类型的 new 对象,则应该以其他方式使用继承多态性(我认为这比@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() 方法。我怀疑是否有可能在不诉诸反思的情况下不覆盖而做到这一点。

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2020-04-12
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    相关资源
    最近更新 更多