Created
February 26, 2020 06:16
-
-
Save kvverti/30058040da2def4116b79c72efc03d34 to your computer and use it in GitHub Desktop.
Java Access Control
This file contains 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 access; | |
public class AccessTest { | |
public static void main(String[] args) { | |
UseM.use(new q.Sub()); // prints "Subclass" | |
// new q.Sub().m(); // compiler error - cannot access protected method m | |
((p.Super)new q.Sub()).m(); // prints "Subclass" | |
} | |
} |
This file contains 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 q; | |
public class Sub extends p.Super { | |
protected void m() { | |
System.out.println("Subclass"); | |
} | |
} |
This file contains 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 p; | |
public class Super { | |
// compile with protected first, then public | |
protected | |
// public | |
void m() { | |
System.out.println("Superclass"); | |
} | |
} |
This file contains 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 access; | |
public class UseM { | |
// a method that uses the public superclass method | |
public static void use(p.Super obj) { | |
obj.m(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment