Reputation: 75
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!
Upvotes: 3
Views: 480
Reputation: 14217
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
Upvotes: 6
Reputation: 3365
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.
Upvotes: 2