객체를 만들기 위한 설계도.
속성(필드)과 동작(메서드)을 묶어서 표현.
예시:
public class Car {
private String brand;
private int speed;
public Car(String brand) {
this.brand = brand;
this.speed = 0;
}
public void accelerate() {
speed += 10;
}
public int getSpeed() {
return speed;
}
}
특정 기능의 약속을 정의하는 것.
구현체 클래스는 반드시 인터페이스의 메서드를 구현해야 함.
다형성을 활용할 수 있음.
public interface Animal {
void makeSound();
}
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("멍멍");
}
}
객체 간의 의존성을 직접 만들지 않고 외부에서 주입하는 방식.
Spring에서는 @Autowired나 생성자 주입 방식으로 많이 사용.
예시:
@Service
public class OrderService {
private final PaymentService paymentService;
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
public void order() {
paymentService.pay();
}
}