在scala中访问java基类的静态成员

编程入门 行业动态 更新时间:2024-10-24 14:23:50
本文介绍了在scala中访问java基类的静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些用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基类的静态成员

本文发布于:2023-07-15 10:21:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110638.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   成员   scala   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!