final은 변경을 막는 키워드이며 변수, 메서드, 클래스에 사용됨.public final class Animal {
public final void eat() {
System.out.println("먹는다");
}
}
static final: 상수를 만들 때 사용 (ex. public static final String NATION = "대한민국";)public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
외부에서는
Singleton.getInstance()로 접근.
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 | 예외를 호출한 쪽으로 전달 |