개발/자바

메소드 접근 제어자 public, protected, private, default

피터JK 2025. 2. 18. 10:34
728x90

Java에서 메소드의 접근 제어자는 클래스 및 객체의 멤버(필드, 메소드 등)에 대한 접근을 제한하는 역할을 합니다. Java에서 제공하는 접근 제어자는 다음과 같습니다.

1. public (공개 접근 제어자)

  • 어디서든 접근 가능
  • 같은 클래스, 같은 패키지, 다른 패키지에서도 접근 가능
  • 예제
    public class Example {
        public void publicMethod() {
            System.out.println("Public method");
        }
    }
    
    class AnotherClass {
        public static void main(String[] args) {
            Example example = new Example();
            example.publicMethod(); // 가능
        }
    }

2. protected (보호된 접근 제어자)

  • 같은 패키지 내에서는 자유롭게 접근 가능
  • 다른 패키지에서는 상속받은 경우에만 접근 가능
  • 예제
    class Parent {
        protected void protectedMethod() {
            System.out.println("Protected method");
        }
    }
    
    class Child extends Parent {
        public void callMethod() {
            protectedMethod(); // 가능 (상속받았기 때문)
        }
    }
    package another;  // 다른 패키지
    
    import Parent;
    
    class Test {
        public static void main(String[] args) {
            Parent p = new Parent();
            p.protectedMethod(); // 오류 발생 (상속받지 않았기 때문)
        }
    }

3. private (비공개 접근 제어자)

  • 해당 클래스 내에서만 접근 가능
  • 같은 패키지여도 다른 클래스에서는 접근 불가능
  • 상속받아도 접근 불가능
  • 예제
    class Example {
        private void privateMethod() {
            System.out.println("Private method");
        }
    
        public void callPrivate() {
            privateMethod(); // 가능 (같은 클래스 내부이므로)
        }
    }
    
    class AnotherClass {
        public static void main(String[] args) {
            Example example = new Example();
            // example.privateMethod(); // 오류 발생 (다른 클래스에서 접근 불가)
        }
    }

4. (default) 패키지 접근 제어자

  • 별도의 접근 제어자를 지정하지 않으면 적용됨
  • 같은 패키지 내에서만 접근 가능, 다른 패키지에서는 접근 불가능
  • 예제
    class Example {
        void defaultMethod() {
            System.out.println("Default method");
        }
    }
    
    class SamePackageClass {
        public static void main(String[] args) {
            Example example = new Example();
            example.defaultMethod(); // 가능 (같은 패키지)
        }
    }
    package another;  // 다른 패키지
    
    import Example;
    
    class Test {
        public static void main(String[] args) {
            Example example = new Example();
            example.defaultMethod(); // 오류 발생 (다른 패키지에서 접근 불가)
        }
    }
    

정리

접근 제어자 같은 클래스 같은 패키지  다른 패키지 (상속 X)  다른 패키지 (상속 O)
public O O O O
protected O O X O
(default) O O X X
private O X X X

이렇게 접근 제어자를 활용하면 캡슐화(Encapsulation) 를 통해 데이터 보호와 코드 유지보수를 쉽게 할 수 있습니다.

 

2025.02.18 - [개발/자바] - protected 접근 제어자 다른 패키지 상속 방법

728x90