Encapsulation(=캡슐화)

2025. 11. 28. 14:07·java

# 캡슐화(Encapsulation)

캡슐화란 변수와 함수를 하나의 단위로 묶는 것이다.
클래스는 변수 + getter/setter + 메서드를 묶어 객체를 정의한다.
외부에서 객체의 내부 상태를 직접 변경하지 못하도록 private 접근 제한자를 사용한다.

예제: 시간 클래스

public class TimeT {
    private int hour;

    public int getHour() {
        return hour;
    }

    public boolean setHour(int hour) {
        if (hour < 0 || hour > 24) return false;
        this.hour = hour;
        return true;
    }
}
hour 변수를 직접 접근하지 않고 getter/setter를 통해 안전하게 접근
내부 로직(0~24 범위 제한)을 외부에서 몰라도 안전하게 사용할 수 있음

# 정보 은닉(Information Hiding)

타입 은닉(Type Hiding)

변수나 매개변수 타입을 상위 클래스/인터페이스로 선언
실제 객체는 하위 클래스 객체이지만, 외부에서는 구체 클래스가 숨겨져 있음
장점: 구현 변경 시 외부 코드 영향 최소화
public class Shape {
    public void draw() {
        System.out.println("Shape Draw");
    }
}

class Rectangle extends Shape {
    @Override
    public void draw() {
        System.out.println("Rectangle Draw");
    }
}

class InformationUse {
    public void drawNow(Shape shape) {
        shape.draw(); // 타입 은닉
    }
}

class Main {
    public static void main(String[] args) {
        var use = new InformationUse();
        use.drawNow(new Rectangle());
    }
}
Factory Pattern과 결합하면 Main 클래스에서는 구체 클래스 존재를 몰라도 객체 생성 가능
enum ShapeConst { TRIANGLE, RECTANGLE }

class ShapeFactory {
    public static Shape createShape(ShapeConst shape) {
        return switch (shape) {
            case RECTANGLE -> new Rectangle();
            case TRIANGLE -> new Rectangle(); // 예시
        };
    }
}

class MainFactory {
    public static void main(String[] args) {
        var use = new InformationUse();
        use.drawNow(ShapeFactory.createShape(ShapeConst.RECTANGLE));
    }
}

필드 및 메소드 은닉

클래스 내부 동작에 필요한 메서드를 private으로 선언
외부에서는 public 메서드를 통해서만 접근 가능
public class MethodT {
    private void init() { System.out.println("init"); }
    private void process() { System.out.println("process"); }
    private void release() { System.out.println("release"); }

    public void work() {
        init();
        process();
        release();
    }
}

class Main1 {
    public static void main(String[] args) {
        new MethodT().work();
    }
}
외부에서는 work()만 호출 가능, 내부 구현(init, process, release)은 숨김
내부 구현 변경이 가능하고 외부 코드 영향 없음

구현 은닉(Abstraction)

추상 클래스(Abstract Class)와 인터페이스를 통해 구현체를 숨김
외부에서 객체를 사용할 때 구체적 구현 내용 몰라도 동작 가능
public abstract class Notification {
    protected String recipient;

    public Notification(String recipient) {
        this.recipient = recipient;
    }

    public void notifyUser() {
        System.out.println("알림을 " + recipient + " 전달합니다.");
        sendNotification(); // 구체적 구현 호출
    }

    protected abstract void sendNotification(); // 구현 은닉
}

class SMSNotification extends Notification {
    public SMSNotification(String recipient) {
        super(recipient);
    }

    @Override
    protected void sendNotification() {
        System.out.println("SMS 알림 전송");
    }
}

class Main2 {
    public static void main(String[] args) {
        Notification sms = new SMSNotification("010-2222-2222");
        sms.notifyUser(); // 외부에서는 sendNotification 내부 구현을 모름
    }
}
장점: 알림 방식 변경(SMS → Email) 시 Main 코드는 변경 불필요
추상화 + 캡슐화 = 유지보수성과 확장성 극대화

개념 특징 예시
캡슐화 변수+메서드 하나의 클래스 단위로 묶음 TimeT 클래스
정보 은닉 외부에서 내부 구현을 보이지 않게 함 private 메서드, getter/setter
타입 은닉 매개변수/리턴 타입을 상위 클래스로 선언 Shape → Rectangle
구현 은닉 추상 클래스/인터페이스를 통해 구현 숨김 Notification 추상 클래스
Factory Pattern 객체 생성 로직 은닉 ShapeFactory.createShape()

'java' 카테고리의 다른 글

Generic Type(=제네릭 타입)  (0) 2025.11.28
Abstract class(=추상화)  (0) 2025.11.28
Java 문법 – Overload vs Override  (0) 2025.11.28
Java 문법 – 변수, 메서드, 다형성, CallByValue/Reference  (0) 2025.11.28
Java 문법 - 클래스, 진법, 비트 연산  (0) 2025.11.28
'java' 카테고리의 다른 글
  • Generic Type(=제네릭 타입)
  • Abstract class(=추상화)
  • Java 문법 – Overload vs Override
  • Java 문법 – 변수, 메서드, 다형성, CallByValue/Reference
차하비
차하비
chadev 님의 블로그 입니다.
  • 차하비
    chadev
    차하비
  • 전체
    오늘
    어제
    • 분류 전체보기 (47)
      • kubernetes, k8s (3)
      • docker (3)
      • cloud (6)
      • linux (12)
      • spring (7)
      • java (11)
      • error (4)
      • 자격증 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Spring
    restAPI
    monolithic
    OOP
    클래스
    진법
    url
    Join
    docker
    HTTP
    Kubernetes
    모놀리식
    KUBECTL
    thread
    비트 연산
    URI
    k8s
    객체지향
    Java
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
차하비
Encapsulation(=캡슐화)
상단으로

티스토리툴바