본문 바로가기

JAVA

JAVA-(2022.05.10)-interface의 static 메소드

static메소드

 

- interface에서 static메소드를 통해 메소드를 구현할 수 있다.

- 재정의가 불가능하다(static이니깐 당연하다는 맥락으로 이해하면 될듯).

- 접근 제어자는 항상 public이며 생략할 수 있다.

- 인터페이스를 직접 참조하여(레퍼런스) 사용해야만 한다. 

 

 

 

코드예시)

 

1) 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);
        }
    }

 

 

 

 

 

 

 

 

 

 

 

 

*본 게시물은 프로그래머스<자바입문>강의를 복습하며 작성한 글입니다.