Last active
July 20, 2022 09:08
-
-
Save tomsontom/25beb712197a8c2796ca530d9d0cdd5d to your computer and use it in GitHub Desktop.
Java Visibility Puzzler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sampler; | |
public class Base { | |
void packageMethod() { | |
System.err.println("Package on " + getClass()); | |
} | |
protected void protectedMethod() { | |
System.err.println("Protected on " + getClass()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Author
tomsontom
commented
Jul 20, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment