<< Upgraded Weblog Software To Pebble 2.3.1 | Home | Neal Gafter: Core Team That Guides Java >>

Friday Java Quiz: protected

Brian Goetz made the following claim on the openjfx-compiler project mailing list:

Brian Goetz: In fact, I'll bet that many java developers would be surprised to learn what "protected" really means in Java. Even language experts get confused on these points.

So what does protected really mean? Let's find out if you know the answer.

Q: Will the following Java source files compile together? Will Main run without exceptions? If so, what will be printed?

// base/Base.java
package base;
public class Base {
  protected int i;
  public Base(int i) {
    this.i = i;
  }
}
// derived/Derived.java
package derived;
import base.*;
public class Derived extends Base {
  public Derived(int i) {
    super(i);
  }
  public void foo(Base b) {
    System.out.println(b.i);
  }
}
// Main.java
public class Main {
  public static void main(String[] args) {
    Derived d = new Derived(1024);
    d.foo(d);
  }
}

Today's semi-relaxed rules: no running the compiler, but you can consult the JLS.

Tags :


Re: Friday Java Quiz: protected

iirc - "protected" makes a member package private. Meaning that access by classes outside the package (even ones that extend) to protected members inside a package are treated as though they had attempted to access a private member. So the line: System.out.println(b.i); Will probably present a problem, as it's being used by a class in the "derived" package instead of "base".

Re: Friday Java Quiz: protected

System.out.println(b.i) will not compile. An access to anInstance.aField will work only if 1) aField is public 2) aField is protected and the current class and the Class of anInstance are in the same package. 3) aField is private the current class and the Class of anInstance are the same. The same goes for aMethod() :)

hehe, i knew it :P

i met one of those java experts on job interview and he belived that protected is only "in subclass". so no news here.

Re: Friday Java Quiz: protected

Change it to "System.out.println(i)" and it will compile.

Re: Friday Java Quiz: protected

Although the JLS seems to be somewhat unclear on this point, the "Point" and "Point3d" example is similar enough to this example to make this clear. The "b.i" reference in the "Derived.foo()" method fails to compile because "foo()" is "not involved with the implementation" of Base, but of Derived. Oddly, if "foo()" took a parameter of type "Derived" instead, it should pass the compiler.

Re: Friday Java Quiz: protected

The statement will not compile. Protected field can not be accessed from another package.

Add a comment Send a TrackBack