접근 제어자(access modifier)
- 클래스 -> 패키지 -> 자바 구조에서 클래스 간의 접근을 제어할 때 사용한다.
- private -> default -> protected -> public
# Java > Main.java
import pkg.ModifierTest;
class Child extends ModifierTest {
void callParentProtected(){
System.out.println("call my parent's protected method");
super.massageProtected();
}
}
public class Main {
public static void main(String[] args) {
ModifierTest modifierTest = new ModifierTest();
modifierTest.massageOutside();
// modifierTest.massageInside(); //compile error
// modifierTest.massageProtected(); //compile error
// modifierTest.massagePackagePrivate(); //compile error
Child child = new Child();
child.callParentProtected();
}
}
# Java > pkg > Modifier.java
package pkg;
public class ModifierTest {
private void massageInside(){
System.out.println("This is private modifier");
}
public void massageOutside(){
System.out.println("This is public modifier");
massageInside();
}
protected void massageProtected(){
System.out.println("This is protected modifier");
}
void massagePackagePrivate(){
System.out.println("this is package private modifier");
}
}
protected
- 같은 패키지에서는 접근 제한이 없지만, 다른 패키지에서는 자식 클래스에서만 접근할 수 있다.
- 필드, 생성자, 메소드 선언에 사용될 수 있다.
- 다른 패키지의 자식 클래스에서 접근 시 new를 사용하여 직접 호출 할 수 없고, super로 특정 생성자를 호출할 수 있다.
- 참고링크