Java 인터페이스와 추상클래스

자바에서 추상화를 구현하는 두 가지 핵심 도구인 인터페이스(Interface)와 추상 클래스(Abstract Class)의 차이점과 활용법을 분석한다.

추상 클래스: 미완성 설계도

추상 클래스는 공통적인 특징을 가진 클래스들의 부모 역할을 수행하며, 하나 이상의 추상 메서드를 포함할 수 있다.

abstract class Animal {
    protected String name;

    // 일반 메서드: 공통 로직 제공
    void eat() {
        System.out.println(name + " is eating.");
    }

    // 추상 메서드: 자식 클래스에서 반드시 구현해야 함
    abstract void makeSound();
}

class Dog extends Animal {
    Dog(String name) { this.name = name; }

    @Override
    void makeSound() {
        System.out.println("Woof Woof");
    }
}

인터페이스: 행위의 규약

인터페이스는 클래스가 수행해야 하는 동작을 정의하며, 다중 구현이 가능하다는 점이 최대 강점이다.

interface Flyable {
    void fly(); // 모든 메서드는 기본적으로 public abstract
}

interface Swimmable {
    void swim();
}

// 여러 인터페이스를 동시에 구현 가능
class Duck extends Animal implements Flyable, Swimmable {
    Duck(String name) { this.name = name; }

    @Override
    void makeSound() { System.out.println("Quack"); }

    @Override
    public void fly() { System.out.println(name + " is flying."); }

    @Override
    public void swim() { System.out.println(name + " is swimming."); }
}

핵심 차이점 비교

| 항목 | 추상 클래스 (Abstract Class) | 인터페이스 (Interface) |

| :— | :— | :— |

| 상속/구현 | extends (단일 상속) | implements (다중 구현) |

| 변수 | 멤버 변수(필드) 가질 수 있음 | 상수(public static final)만 가능 |

| 목적 | 상속을 통한 기능 확장 및 공통점 공유 | 특정 기능을 수행할 수 있다는 약속(규약) |

P.S

추상 클래스는 “is-a” 관계에서 공통된 상태와 행위를 공유할 때 적합하며, 인터페이스는 “has-a” 또는 “can-do” 관계에서 클래스의 종류와 상관없이 공통된 기능을 강제할 때 효율적이다.

현대적인 설계에서는 인터페이스 중심의 설계를 통해 결합도를 낮추는 방식을 권장하는 것 같다.

Author avatar

웨이호프

WordPress creator and blogger.

View all posts