在java中同一个包中,其它类能够访问本类中的protected成员,其它包中本类的子类能够访问本类的protected成员,但其它类则不能访问本类的protected成员。那么scala中是否是也是这样的权限呢? 咱们作个实验:java
joe@joe-Aspire-Z3730:/media/sdb4/download/scala/testdemo/protecteddemo$ gedit protectedtest.scala package p{ class Super{ protected def f(){println(s"protected \n test")} } class Sub extends Super{ f() } class Other{ (new Super()).f() } }
而后编译代码,出现以下提示:scala
joe@joe-Aspire-Z3730:/media/sdb4/download/scala/testdemo/protecteddemo$ scalac protectedtest.scala protectedtest.scala:10: error: method f in class Super cannot be accessed in p.Super Access to protected method f not permitted because enclosing class Other in package p is not a subclass of class Super in package p where target is defined (new Super()).f() ^ one error found
咱们将(new Super()).f()这行代码换成能够正常执行的语句,如:println("other .....")再进行编译则成功。 这个实验说明在scala中,同一个包中,不是子类的话,则不能访问另外一个类中的protected成员,那么能够推出,不是同一个包中的类,更不可能访问本包中的某个类的protected成员。code