[java] 자바 추상 클래스와 인터페이스를 구현한 예시 코드

자바에서 추상 클래스와 인터페이스는 다형성과 객체 지향 프로그래밍의 핵심 개념을 구현하는 데 사용됩니다. 이러한 개념은 코드 재사용성과 유연성을 높여줄 뿐만 아니라, 코드의 가독성을 향상시키는 역할을 합니다.

추상 클래스

추상 클래스는 일반 클래스와 달리 객체를 직접 생성할 수 없으며, 상속을 통해 자식 클래스에서 구현해야 합니다. 이는 추상 클래스가 하위 클래스에게 메서드의 구현을 강제하는 역할을 수행하기 때문입니다.

다음은 추상 클래스를 구현하는 예시 코드입니다.

abstract class Animal {
    protected String name;

    public Animal(String name) {
        this.name = name;
    }

    // 일반 메서드
    public void eat() {
        System.out.println(name + " is eating.");
    }

    // 추상 메서드 - 하위 클래스에서 반드시 구현해야 함
    public abstract void sound();
}

class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }

    public void sound() {
        System.out.println(name + " is barking.");
    }
}

class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }

    public void sound() {
        System.out.println(name + " is meowing.");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog("Charlie");
        dog.eat();
        dog.sound();

        Animal cat = new Cat("Lucy");
        cat.eat();
        cat.sound();
    }
}

위의 예시 코드에서 Animal 클래스는 추상 클래스로 정의되어 있습니다. eat() 메서드는 구현이 되어있는 일반적인 메서드이지만, sound() 메서드는 추상 메서드로 선언되어 있어 하위 클래스에서 반드시 구현해야 합니다. Dog와 Cat 클래스는 Animal 클래스를 상속하여 sound() 메서드를 구현하였습니다.

Main 클래스에서는 Dog와 Cat 객체를 생성하여 eat() 메서드와 sound() 메서드를 호출합니다.

추상 클래스를 사용하면 다형성을 통해 여러 동물의 특성을 공통적으로 처리할 수 있으며, 새로운 동물을 추가할 때도 코드의 수정이 최소화됩니다.

인터페이스

인터페이스는 추상 클래스와 비슷한 개념으로, 클래스가 특정 메서드를 구현하도록 강제하는 역할을 합니다. 하지만 추상 클래스와 달리 다중 상속과 같은 기능을 제공합니다.

다음은 인터페이스를 구현하는 예시 코드입니다.

interface Shape {
    double calculateArea();
    double calculatePerimeter();
}

class Rectangle implements Shape {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double calculateArea() {
        return width * height;
    }

    public double calculatePerimeter() {
        return 2 * (width + height);
    }
}

class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double calculateArea() {
        return Math.PI * radius * radius;
    }

    public double calculatePerimeter() {
        return 2 * Math.PI * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape rectangle = new Rectangle(5, 10);
        System.out.println("Rectangle Area: " + rectangle.calculateArea());
        System.out.println("Rectangle Perimeter: " + rectangle.calculatePerimeter());

        Shape circle = new Circle(3);
        System.out.println("Circle Area: " + circle.calculateArea());
        System.out.println("Circle Perimeter: " + circle.calculatePerimeter());
    }
}

위의 예시 코드에서 Shape 인터페이스는 calculateArea()와 calculatePerimeter() 메서드를 선언하고 있습니다. Rectangle과 Circle 클래스는 인터페이스를 구현하여 해당 메서드를 구현하였습니다.

Main 클래스에서는 Rectangle과 Circle 객체를 생성하여 calculateArea() 및 calculatePerimeter() 메서드를 호출합니다.

인터페이스를 사용하면 클래스가 여러 개의 인터페이스를 구현할 수 있으며, 기능을 유연하게 확장할 수 있습니다.