Search code examples
javascalajvmprotected

How protected method in scala works on jvm


I'm new to Scala. I read that protected keyword of Scala is different from protected in Java. When I've seen the byte code generated for protected method of a public class in Scala and java, I found following:

Scala code:

package com.test 
class Vehicle {
  protected def ignite() {
    println("Ignition.....")
  }
}

when I decompiled using javap, it shows the following code:

public class com.test.Vehicle {
  public void ignite();
  public com.test.Vehicle();
}

And also flags: ACC_PUBLIC is set in descriptor of method ignite for Scala.

Equivalent Java code:

package com.test;
public class Vehicle {
  protected void ignite() {
    System.out.println("Ignition.....");
  }
}

and de-compiled code:

public class com.test.Vehicle {
  public com.test.Vehicle();
  protected void ignite();
}

And also flags: ACC_PROTECTED is set in descriptor of method ignite for Java.

But still it gives the different behavior than JAVA.

How this thing is handled by JVM?

Note: I've not depth knowledge of JVM Specification.


Solution

  • Scala protected (and other qualifiers which don't correspond directly to any JVM qualifiers) is not handled by JVM at all; it's enforced only by the Scala compiler and only for Scala, so any other languages can access this method (since it's public so far as JVM is concerned).