7

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

Mechanical snail
  • 29,755
  • 14
  • 88
  • 113
Mike
  • 225
  • 1
  • 11
  • 2
    If there are no access modifiers on the base class they have to be in the same package, else this won't work. – siebz0r Aug 20 '12 at 07:59
  • sorry, we do have public modifier on the base class, but still doesn't work. – Mike Aug 20 '12 at 09:26
  • How about saying what the problem is? Any error message? – Luigi Plinge Aug 20 '12 at 10:15
  • 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 Aug 20 '12 at 10:20

1 Answers1

9

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.

DaoWen
  • 32,589
  • 6
  • 74
  • 101
  • Thanks, I have to do it this way for now – Mike Aug 20 '12 at 12:16
  • Is that true for protected methods? In particular protected constructors? – om-nom-nom Sep 20 '12 at 00:37
  • @om-nom-nom - There are similar issues with accessing protected members of an ancestor's companion object, but other than that I think you'll be OK for non-static methods/constructors. – DaoWen Sep 20 '12 at 01:00
  • @DaoWen I'm asking because right now I have problems extending guava's [FinalizablePhantomReference](http://code.google.com/p/google-collections/source/browse/trunk/src/com/google/common/base/FinalizablePhantomReference.java?r=69#32) and thinking is this desired behaviour or should I report it – om-nom-nom Sep 20 '12 at 01:08