在扩展Java类时,在Scala中实例化嵌套类

时间:2012-09-10 14:56:08

标签: java scala

我有抽象的java类,其中包含声明为protected static的嵌套类:

public abstract class AbstractJavaClass {
  // contains nested class
  protected static class InnerClass {
  ...
  }
}

当我尝试在Scala类中实例化它时,像在java中那样扩展AbstractJavaClass(即只是在方法new InnerClass中引用名称):

class ScalaClass extends AbstractJavaClass {
   def method = new InnerClass()
}

我收到错误:类型InnerClass不是ScalaClass的成员。我究竟做错了什么?在java中也一样。

1 个答案:

答案 0 :(得分:0)

在这里偶然发现:access java base class's static member in scala

它说

This isn't possible in Scala. Since Scala has no notation of static you can't
access protected static members of a parent class. This is a known limitation.

虽然我无法解决初始问题(当课程为protected static时),但当我在public static的定义中将其更改为AbstractJavaClass时,我可以这样使用它:

class ScalaClass extends AbstractJavaClass {
  import AbstractJavaClass.InnerClass

  def method = new InnerClass
}

使用new InnerClass而不导入会产生同样的错误。