Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

공부 일지

접근 제한자(Access Modifiers) 개념 정리 본문

국비지원/JAVA

접근 제한자(Access Modifiers) 개념 정리

모로노이 2024. 6. 22. 18:41
#접근 제한자
    1. public : 모든 클레스에서 접근 가능.
    2. protected : 같은 패키지 내의 클래스 or 다른 패키지의 상속 클래스에서 접근 가능
    3. default : 같은 패키지 내의 클래스에서 접근 가능.
    4. private : 같은 클래스 내에서만 접근 가능
    	
        // public ex
        
    package ex;
    
    public class Animal {
        public String name;

        public void sound() {
            System.out.println("동물이 소리를 냅니다.");
        }

        public static void main(String[] args) {
            Animal animal = new Animal();
            animal.name = "사자"; // 접근 가능
            animal.sound(); 	  // 접근 가능
        }
    }
// protected ex
// 다른 패키지의 서브클래스에서 접근
package com.other;

import ex.Animal;

public class Lion extends Animal {
    public void roar() {
        name = "사자"; // 접근 가능
        Sound(); // 접근 가능
        System.out.println("사자가 울부짖습니다.");
    }
}
package ex;

    class Animal {
        String name; // default 접근 제한자
        void Sound() { // default 접근 제한자
            System.out.println("동물이 소리를 냅니다.");
        }
    }

    public class Main {
        public static void main(String[] args) {
            Animal animal = new Animal();
            animal.name = "사자"; // 접근 가능
            animal.Sound(); // 접근 가능
        }
    }
// private ex
    public class Animal {
        private String name;

        private void Sound() {
            System.out.println("동물이 소리를 냅니다.");
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void callSound() {
            Sound();
        }
    }
    public class Main {
        public static void main(String[] args) {
            Animal animal = new Animal();
            animal.name = "사자"; // 접근 불가능 - 컴파일 오류 발생
            animal.Sound(); // 접근 불가능 - 컴파일 오류 발생

            animal.setName("사자"); // 접근 가능
            System.out.println(animal.getName()); // 접근 가능
            animal.callSound(); // 접근 가능
        }
    }