인터페이스를 사용하는 이유(다형성)


<aside> 1️⃣ 인터페이스 방식을 사용하는 이유

</aside>

<aside> 2️⃣ 다형성

</aside>

public interface Animal {
    void sound();
}

public class Dog implements Animal {
    @Override
    public void sound() {
        System.out.println("Woof!");
    }
}

public class Cat implements Animal {
    @Override
    public void sound() {
        System.out.println("Meow!");
    }
}
public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        Animal myCat = new Cat();
        myDog.sound();  // Prints "Woof!"
        myCat.sound();  // Prints "Meow!"
    }
}

<aside> 3️⃣ 개방-폐쇄 원칙(OCP)

</aside>

public class Product {
    private String name;
    private double price;
    // constructors, getters and setters...
}

public class ProductSorter {
    public List<Product> sortByPrice(List<Product> products) {
        // sort products by price and return
    }
}
// 인터페이스를 만들어서 추상화시켰다.
public interface ProductSortStrategy {
    List<Product> sort(List<Product> products);
}

public class PriceSortStrategy implements ProductSortStrategy {
    @Override
    public List<Product> sort(List<Product> products) {
        // sort by price and return
    }
}

public class NameSortStrategy implements ProductSortStrategy {
    @Override
    public List<Product> sort(List<Product> products) {
        // sort by name and return
    }
}