6
votes

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 code:

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

1
If there are no access modifiers on the base class they have to be in the same package, else this won't work. - siebz0r
sorry, we do have public modifier on the base class, but still doesn't work. - Mike
How about saying what the problem is? Any error message? - Luigi Plinge
seems when we place the two classes in different packages, we will get compile error: variable a in object B cannot be accessed in object com.fcy.sss.B Access to protected variable a not permitted because enclosing class class D is not a subclass of object B in package sss where target is defined These are the files: B.java file: package com.fcy.sss; public class B { protected static int a = 30; } D.scala file: import com.fcy.sss.B class D extends B{ println(B.a); } - Mike

1 Answers

9
votes

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; }
}

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.