Interface (feat. default method, static method)

김운채·2023년 5월 7일
0

Java

목록 보기
8/11

저번에 인터페이스란 뭔지 공부했었는데, 👉 인터페이스란?
인터페이스의 default method, static method는 따로 다루면 좋을 것 같아서 따로 정리해보려 한다.

기존에 인터페이스는 추상메서드만 정의할 수 있었다.
근데 Java8(JDK 1.8) 부터는 default method, static method를 정의할 수 있게 되었다.
그래서 인터페이스를 구현한 클래스에서는 default method를 오버라이딩 할 수 있다.

왜 default method를 추가했을까?

만약 인터페이스에 새로운 메서드를 추가하게되면, 추상메서드는 구현을 강제하고 있기 때문에, 그 인터페이스를 구현하는 모든 클래스들이 해당 메서드를 구현해야되는 문제가있다.

만약 그 인터페이스를 구현한 클래스들이 겁나 많다면? 엄청난 수의 클래스를 수정해야한다. 아찔하다.

이런 문제를 유연하게 해결하기 위해 인터페이스에 디폴트 메서드를 구현해 놓을 수 있도록 추가 해놓은 것이다.
사실상 추상메서드의 집합이라는 인터페이스 원칙을 위반하는 것이다.

추상메서드 : 구현부가 없는 아직 완성되지 않은 메서드

public interface Calculator {

    public int plus(int i, int j);
    public int minus(int i, int j);

    default int multiple(int i, int j){
        return i * j;
    }    
}
public class CalculatorMain implements Calculator{
    @Override
    public int plus(int i, int j) {
        return i+j;
    }

    @Override
    public int minus(int i, int j) {
        return i-j;
    }

    public static void main(String[] args) {
        Calculator calculator = new CalculatorMain();
        int multipleValue = calculator.multiple(10, 20);
        System.out.println("multipleValue = " + multipleValue);
    }
}

만약 내가 더하기, 빼기만 있는 계산기를 만들었다. 근데 후에 곱하기 기능을 추가해줘야 한다. 근데 내가 만든 계산기를 이미 여기저기서 구현하고 있었던 것이다.
그럼 울지말고 아무일 없었던 것처럼 default 메서드를 추가해주면 되는 것이다.👩

기존에 인터페이스가 추상메서드만 가지고 있었던 이유는 충돌 때문이었다.
근데 defualt 메소드가 추가 되면서 충돌 문제가 다시 생긴거다.

  • 만약 여러 인터페이스의 같은 디폴트 메서드간의 충돌이 생긴다면
    => 인터페이스르 구현한 클래스에서 디폴트 메서드를 오버라이딩 하면 된다.

  • 디폴트 메서드와 조상클래스의 메서드 간의 충돌이 생긴다면
    => 조상클래스 메서드가 우선으로 상속되고 디폴트 메서드는 무시된다.

왜 static method를 추가했을까?

인터페이스안에 static 메소드를 선언함으로써 인터페이스를 이용해 간단한 기능을 가지는 유틸리티성 인터페이스를 만들 수 있다.
static 메서드는 반드시 인터페이스명.메서드명() 로 호출헤야한다.
static 메소드는 override 불가능하다.

public interface CalculatorStatic {

    public int plus(int i, int j);
    public int minus(int i, int j);

    pblic static int multiple(int i, int j){
        return i * j;
    }    
}
public class CalculatorMain implements CalculatorStatic{
    @Override
    public int plus(int i, int j) {
        return i+j;
    }

    @Override
    public int minus(int i, int j) {
        return i-j;
    }

    public static void main(String[] args) {
        int multipleValue = CalculatorStatic.multiple(10, 20);
        System.out.println("multipleValue = " + multipleValue);
    }
}

참고 자료 : https://n1tjrgns.tistory.com/289

0개의 댓글