목차

    ⏳ Time Log/1. One Day (Daily · TIL)

    [TIL] Day 08 — Java 접근 제어자와 캡슐화, static

    this.Serena 2026. 2. 18. 23:38

    [TIL] Day 08 — Java 접근 제어자와 캡슐화, static

    날짜: 2025-10-29
    기술 스택: Java OOP 캡슐화 static getter/setter
    부트캠프: 풀스택 개발자 부트캠프 2주차


    접근 제어자 (Access Modifier)

    제어자 클래스 내부 같은 패키지 자식 클래스 외부
    private
    default
    protected
    public

    암기법: 프디프퍼 (private → default → protected → public, 범위 순서)


    캡슐화 + getter/setter

    public class Person {
        private String name; // 외부 직접 접근 차단
        private int age;
    
        // getter
        public String getName() { return name; }
        public int getAge()     { return age; }
    
        // setter
        public void setName(String name) {
            this.name = name; // this.로 필드와 매개변수 구분
        }
        public void setAge(int age) {
            if (age >= 0) this.age = age; // 유효성 검사 로직 삽입 가능
        }
    }
    
    // 사용
    Person p = new Person();
    p.setName("홍길동");
    System.out.println(p.getName());
    • Eclipse: 소스 우클릭 → Source → Generate Getters and Setters 자동 생성

    생성자 (Constructor)

    public class Car {
        String color;
        int speed;
    
        // 기본 생성자 (명시적 작성 권장)
        Car() {}
    
        // 오버로딩 생성자
        Car(String color) { this.color = color; }
        Car(String color, int speed) {
            this.color = color;
            this.speed = speed;
        }
    }
    • 생성자 없으면 컴파일러가 자동으로 기본 생성자 생성
    • 다른 생성자 작성 시 기본 생성자 자동 생성 안 됨 → 두 개 다 직접 작성

    static 멤버

    public class MathUtil {
        static final double PI = 3.14159;           // static + final → 상수
        static int add(int a, int b) { return a + b; }    // 객체 없이 호출
        int subtract(int a, int b)   { return a - b; }    // 객체 생성 후 호출
    }
    
    // 사용
    System.out.println(MathUtil.PI);           // 클래스명.static멤버
    System.out.println(MathUtil.add(3, 4));    // 객체 생성 불필요
    MathUtil m = new MathUtil();
    System.out.println(m.subtract(5, 2));      // 객체 필요

    static 상수 선언

    static final double PI = 3.14159;    // 대문자 + 언더바 스타일
    static final int MAX_SIZE = 100;

    메인 메서드 구조

    public static void main(String[] args)
    //  ^      ^     ^    ^       ^
    // 접근제한 정적 반환없음 메서드명 인자(명령행 인자)

    트러블슈팅

    this.a = a vs a = a

    • private 필드와 setter 매개변수 이름이 같으면 this 필수
    • this 없으면 매개변수에 매개변수를 대입하는 무의미한 코드가 됨

    생성자와 일반 메서드 구분

    • 생성자: 클래스명과 동일, 반환형 없음 (void도 제외)
    • 일반 메서드: 반환형 지정 필수

    더 알아볼 것

    • 싱글턴 패턴 (Singleton Pattern) 구현
    • 가변 길이 매개변수 (...varargs) 활용
    • CSS position: relative vs absolute vs fixed 실습
    • CSS input[type="checkbox"]:checked ~ #view 패턴 활용 사례
    • 상속(extends) 기본 문법과 super 키워드