Skip to content

Instantly share code, notes, and snippets.

@kvverti
Created February 26, 2020 06:16
Show Gist options
  • Save kvverti/30058040da2def4116b79c72efc03d34 to your computer and use it in GitHub Desktop.
Save kvverti/30058040da2def4116b79c72efc03d34 to your computer and use it in GitHub Desktop.
Java Access Control
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"
}
}
package q;
public class Sub extends p.Super {
protected void m() {
System.out.println("Subclass");
}
}
package p;
public class Super {
// compile with protected first, then public
protected
// public
void m() {
System.out.println("Superclass");
}
}
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