💻 Programming

Interface

Interface

Defines the methods a class must implement. Key to implementing polymorphism.

📖 Detailed Explanation

An Interface is a kind of contract that defines the signatures (name, parameters, return type) of the methods a class must implement. An interface itself contains no implementation code; it specifies only "what must be done" and delegates "how to do it" to the implementing class.

The core value of an interface is that it enables polymorphism and loose coupling. When different classes implement the same interface, client code can handle them consistently through the interface type without knowing the concrete implementation. This greatly improves the flexibility and extensibility of the code.

In statically typed languages such as Java, C#, and TypeScript, interfaces are directly supported as a language keyword. Even in languages without explicit interfaces, such as Python or Go, similar concepts are implemented through duck typing or protocols. TypeScript uses structural typing, which exists only at compile time and is removed at runtime.

In practice, interfaces are the foundation of various design patterns such as dependency injection (DI), the strategy pattern, and the adapter pattern. In test-driven development (TDD) in particular, mock objects can be easily injected through interfaces, making unit tests much easier to write.

💻 Code Example

// TypeScript 인터페이스 예제

// 1. 기본 인터페이스 정의
interface PaymentProcessor {
    processPayment(amount: number): Promise<boolean>;
    refund(transactionId: string, amount: number): Promise<boolean>;
    getTransactionStatus(transactionId: string): Promise<string>;
}

// 2. 인터페이스 구현 - 신용카드 결제
class CreditCardProcessor implements PaymentProcessor {
    async processPayment(amount: number): Promise<boolean> {
        console.log(`신용카드로 ${amount}원 결제 처리 중...`);
        // 실제 카드사 API 호출 로직
        return true;
    }

    async refund(transactionId: string, amount: number): Promise<boolean> {
        console.log(`거래 ${transactionId}: ${amount}원 환불 처리`);
        return true;
    }

    async getTransactionStatus(transactionId: string): Promise<string> {
        return 'COMPLETED';
    }
}

// 3. 인터페이스 구현 - 카카오페이 결제
class KakaoPayProcessor implements PaymentProcessor {
    async processPayment(amount: number): Promise<boolean> {
        console.log(`카카오페이로 ${amount}원 결제 처리 중...`);
        // 카카오페이 API 호출 로직
        return true;
    }

    async refund(transactionId: string, amount: number): Promise<boolean> {
        console.log(`카카오페이 환불: ${transactionId}`);
        return true;
    }

    async getTransactionStatus(transactionId: string): Promise<string> {
        return 'COMPLETED';
    }
}

// 4. 다형성 활용 - 인터페이스 타입으로 처리
class OrderService {
    // 구체적인 구현체가 아닌 인터페이스에 의존 (느슨한 결합)
    constructor(private paymentProcessor: PaymentProcessor) {}

    async checkout(orderId: string, amount: number): Promise<void> {
        console.log(`주문 ${orderId} 결제 시작`);
        const success = await this.paymentProcessor.processPayment(amount);
        if (success) {
            console.log('결제 완료!');
        }
    }
}

// 사용 예시 - 결제 수단 쉽게 교체 가능
const creditCardService = new OrderService(new CreditCardProcessor());
const kakaoPayService = new OrderService(new KakaoPayProcessor());

await creditCardService.checkout('ORD-001', 50000);
await kakaoPayService.checkout('ORD-002', 30000);

🗣️ Say It Like This in Practice

💬 In a Meeting
"The payment module is tightly coupled to a specific PG provider, so it's hard to replace. If we define a PaymentProcessor interface and create an implementation for each PG provider, we can easily switch to another PG provider later."
💬 In an Interview
"The difference between an interface and an abstract class lies in their purpose. An interface defines a capability—'what it can do'—while an abstract class provides a common foundation—'what it is'. Since Java 8, interfaces can also have default methods, but the difference remains that they still cannot have state (fields)."
💬 In a code review
"This service class is directly creating MySQLRepository, a concrete class. If we create a Repository interface and receive it via constructor injection, we can easily swap it with InMemoryRepository during testing and run unit tests quickly."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Creating Overly Large Interfaces (Fat Interface)

Violating the Interface Segregation Principle (ISP) forces implementations to implement methods they do not use. Split them into small interfaces by role. For example: define Readable and Writable separately.

❌
Confusing Interfaces with Abstract Classes

An interface allows multiple implementation and cannot hold state. If you need shared implementation code or state, use an abstract class. Combining the two is also a good approach.

✅
Interface-Based Design (Program to Interface)

Declare variables, parameters, and return types as interfaces rather than concrete classes. This makes it easier to swap implementations and makes testing and maintenance more convenient.

🔗 Related Terms

📚 Learn More