[英]access java base class's static member in scala
Ihave some codes written in Java. 我有一些用Java编写的代码。 And for new classes I plan to write in Scala. 对于新课程,我打算用Scala编写。 I have a problem regarding accessing the protected static member of the base class. 我有一个关于访问基类的受保护的静态成员的问题。 Here is the sample code: 以下是示例代码:
Java code: Java代码:
class Base{
protected static int count = 20;
}
scala code: 斯卡拉码:
class Derived extends Base{
println(count);
}
Any suggestion on this? 有什么建议吗? How could I solve this without modifying the existing base class 如何在不修改现有基类的情况下解决这个问题
This isn't possible in Scala. 这在Scala中是不可能的。 Since Scala has no notation of static
you can't access protected static
members of a parent class. 由于Scala没有static
符号,因此无法访问父类的protected static
成员。 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; }
}
Now you can inherit from this new class instead and access the static member through the getter/setter methods: 现在,您可以继承此新类,并通过getter / setter方法访问静态成员:
// 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. 这很难看 - 但是如果你真的想要使用protected static
成员那么这就是你必须要做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.