인터페이스 - default method

이상해씨·2023년 5월 8일
0

JAVA

목록 보기
34/40

JAVA 8 로 인한 변경

  • 기존에는 추상 메소드만 생성할 수 있었으나, 8부터 인터페이스에서 defualt 메소드와 static 메소드를 생성할 수 있다.
  • 인터페이스 변경시 인터페이스를 구현하고 있는 모든 클래스들이 해당 메소드를 구현해야 하는 문제를 해결하기 위함

1) default 메소트

  • default 선언시 메소드 구현 가능
  • 이 인터페이스를 구현하는 클래의 경우 , default 메소드 오버라이딩 가능
    public interface Calculator {
        public int plus(int i, int j);
        public int multiple(int i, int j);
        default int exec(int i, int j){      //default로 선언함으로 메소드를 구현할 수 있다.
            return i + j;
        }
    }

    //Calculator인터페이스를 구현한 MyCalculator클래스
    public class MyCalculator implements Calculator {

        @Override
        public int plus(int i, int j) {
            return i + j;
        }

        @Override
        public int multiple(int i, int j) {
            return i * j;
        }
    }

    public class MyCalculatorExam {
        public static void main(String[] args){
            Calculator cal = new MyCalculator();
            int value = cal.exec(5, 10);
            System.out.println(value);
        }
    }

2) static 메소드

  • 인터페이스에 static 선언으로 간단한 기능을 가진 유틸리티성 인터페이스 생성 가능
  • static 매소드 사용시, 인터페이스명.메소드명();으로 사용가능
    public interface Calculator {
        public int plus(int i, int j);
        public int multiple(int i, int j);
        default int exec(int i, int j){
            return i + j;
        }
        public static int exec2(int i, int j){   //static 메소드 
            return i * j;
        }
    }

    //인터페이스에서 정의한 static메소드는 반드시 인터페이스명.메소드 형식으로 호출해야한다.  

    public class MyCalculatorExam {
        public static void main(String[] args){
            Calculator cal = new MyCalculator();
            int value = cal.exec(5, 10);
            System.out.println(value);

            int value2 = Calculator.exec2(5, 10);  //static메소드 호출 
            System.out.println(value2);
        }
    }

참고

profile
공부에는 끝이 없다

0개의 댓글