Skip to content

Instantly share code, notes, and snippets.

@tomsontom
Last active July 20, 2022 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomsontom/25beb712197a8c2796ca530d9d0cdd5d to your computer and use it in GitHub Desktop.
Save tomsontom/25beb712197a8c2796ca530d9d0cdd5d to your computer and use it in GitHub Desktop.
Java Visibility Puzzler
package sampler;
public class Base {
void packageMethod() {
System.err.println("Package on " + getClass());
}
protected void protectedMethod() {
System.err.println("Protected on " + getClass());
}
}
package sampler.internal;
import sampler.Base;
public class Impl extends Base {
// Comment this in and protected access suddenly fails
// @Override
// protected void protectedMethod() { super.protectedMethod(); }
}
package sampler;
import sampler.internal.Impl;
public class User {
public static void main(String[] args) {
Base base = new Base();
Impl impl = new Impl();
base.packageMethod();
impl.packageMethod(); // Compile error
((Base)impl).packageMethod();
base.protectedMethod();
impl.protectedMethod(); // No compile error
// why can I call a protected method
// but not a package-private??? I'm confused
}
}
@tomsontom
Copy link
Author

Bildschirmfoto 2022-07-20 um 10 20 37

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment