3

In a scala class, I have defined a protected field and a protected method:

TestProtected.scala:

class TestProtected {
  protected var f = 0

  protected def m = 1
}

In my opinion, it will convert the protected f and m to a java protected filed and method. But when i use jd-gui to decompiler the TestProtected.class to java file, the result was beyond my expectation:

@ScalaSignature(bytes="...")
public class TestProtected
{
  private int f= 0;

  public int f() { return this.f; } 
  public void f$eq(int x$1) { this.f = x$1; } 
  public int m() {
    return 1;
  }
}

The f and m in java file is public?

Why?

Thanks!

littzh
  • 75
  • 1
  • 8
  • 1
    Probably linked to the fact that `protected` in Scala [doesn't](http://daily-scala.blogspot.fr/2009/11/access-modifiers-public-private.html) mean the same thing as in Java, but I can't put the pieces together. – John K Mar 10 '16 at 10:56

2 Answers2

6

Firstly, Scala protected is different from Java protected:

Java's protected is visible to same package and subclass, Scala protect is only visible to subclass, so Scala's protected is more restrictive than Java's.

So this is caused by JVM Level access modifier is not same as Scala access modifier, we know Scala runs on JVM, for running on JVM, it needs to generate the compatible byte code in JVM.

There are some other example like:

private
private[this]
private[package]

There are some reference about Scala Access:

Protected and private in Scala become public in Java

Scala Access

Protected Members

Suma
  • 33,181
  • 16
  • 123
  • 191
chengpohi
  • 14,064
  • 1
  • 24
  • 42
2

I'm not sure, but this may be because companion object of a class should also be able to access protected members of a class in scala. And because companion object is actually a different class from its companioin class, scala has to compile protected members to public in a bytecode.

vitalii
  • 3,335
  • 14
  • 18