我有一些用Java编写的代码。对于新课程,我打算用Scala编写。我有一个关于访问基类的受保护的静态成员的问题。以下是示例代码:
Ihave some codes written in Java. And for new classes I plan to write in Scala. I have a problem regarding accessing the protected static member of the base class. Here is the sample code:
Java代码:
class Base{ protected static int count = 20; }scala代码:
class Derived extends Base{ println(count); }对此有何建议?如何在不修改现有基类的情况下解决这个问题
Any suggestion on this? How could I solve this without modifying the existing base class
推荐答案这在Scala中是不可能的。由于Scala没有 static 的表示法,因此无法访问父类的 protected static 成员。这是已知限制。
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.
解决方法是执行以下操作:
The work-around is to do something like this:
// Java public class BaseStatic extends Base { protected int getCount() { return Base.count; } protected void setCount(int c) { Base.count = c; } }现在你可以从这个新类继承并通过以下方式访问静态成员getter / setter方法:
Now you can inherit from this new class instead and access the static member through the getter/setter methods:
// Scala class Derived extends BaseStatic { println(getCount()); }这很难看 - 但如果你真的想用保护静态成员那就是你必须要做的事情。
It's ugly—but if you really want to use protected static members then that's what you'll have to do.
更多推荐
在scala中访问java基类的静态成员
发布评论