TIL - 20250703

juni·2025년 7월 3일

TIL

목록 보기
55/316

📘 자바 학습 내용 정리 (0703)

✅ final 키워드

  • final변경을 막는 키워드이며 변수, 메서드, 클래스에 사용됨.
  • final 변수: 초기화 후 값 변경 불가.
  • final 메서드: 오버라이딩 불가능.
  • final 클래스: 상속 불가능.
public final class Animal {
    public final void eat() {
        System.out.println("먹는다");
    }
}
  • static final: 상수를 만들 때 사용 (ex. public static final String NATION = "대한민국";)

✅ Singleton 패턴

  • 객체를 오직 하나만 생성하도록 보장하는 디자인 패턴.
  • 생성자는 private, 유일한 인스턴스를 static으로 내부에 생성.
public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() {
        return instance;
    }
}

외부에서는 Singleton.getInstance() 로 접근.


✅ enum (열거형)

  • 고정된 상수 집합을 표현하는 클래스.
  • enum은 내부에 멤버 필드, 생성자, 메서드까지 포함 가능.
public enum PizzaStatus {
    ORDERED("주문 완료", 10),
    READY("준비 완료", 30),
    DELIVERED("배달 완료", 40);

    private final String description;
    private final int timeToSetup;

    PizzaStatus(String description, int timeToSetup) {
        this.description = description;
        this.timeToSetup = timeToSetup;
    }
}

✅ 추상 클래스 (abstract)

  • 객체 생성은 안 되지만 상속을 위한 설계도 역할을 하는 클래스.
  • 일부는 구현하고, 일부는 자식 클래스에서 오버라이딩 하도록 강제.
public abstract class Pet {
    public abstract void feed();
    public abstract void sleep();
}

✅ 인터페이스 (interface)

  • 모든 메서드가 기본적으로 public abstract.
  • 다중 구현이 가능하며, 객체의 행동을 명세함.
public interface Pet {
    void handle();
    void inject();
}
  • default 메서드로 기본 구현 가능.
  • interface 끼리도 상속 가능.

✅ 예외 처리 (try-catch-finally)

  • 에러가 발생할 수 있는 코드 블럭을 안전하게 실행하기 위한 구문.
  • 예외 발생 시 catch로 이동, 항상 실행되는 코드는 finally에 작성.
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("0으로 나눌 수 없습니다.");
} finally {
    System.out.println("항상 실행됩니다.");
}

✅ 사용자 정의 예외

  • 직접 만든 예외 클래스로 상황에 맞는 예외를 표현할 수 있음.
public class LoginInvalidException extends RuntimeException {
    public LoginInvalidException(String message) {
        super(message);
    }
}
  • 예외 발생 시 throw new LoginInvalidException("메시지"); 사용.

✅ 예외 전파 (throws)

  • 메서드 선언부에 throws를 붙이면, 예외를 호출한 쪽으로 넘김.
public String authenticate(String id, String pw) throws LoginInvalidException {
    if (!id.equals("abc123")) {
        throw new LoginInvalidException("계정이 존재하지 않습니다.");
    }
    return "로그인 성공";
}

✅ 요약표

항목설명
final값/클래스/메서드 변경 금지
Singleton하나의 객체만 생성되도록 보장
enum고정된 상수값의 집합
abstract class일부 구현 + 일부 추상 메서드
interface기능 명세만 존재, 다중 구현 가능
try-catch-finally예외 발생 대비 코드
사용자 정의 예외상황 맞춤 에러 메시지 표현 가능
throws예외를 호출한 쪽으로 전달

0개의 댓글