[Java] 인터페이스

zizi·2023년 5월 3일
0

Java

목록 보기
22/27
  • 인터페이스란 서로 관계가 없는 물체들이 상호 작용을 하기 위해서 사용하는 장치나 시스템이다.
  • 구현은 하지 않고 필요한 기능들만 선언해서 가지고 있는 것이다.

인터페이스 정의하기

  • 인터페이스 정의하는 방법
    • 추상 메소드와 상수를 정의 할 수 있다.
    public interface TV{
        public int MAX_VOLUME = 100;	
        public int MIN_VOLUME = 0;	

        public void turnOn();
        public void turnOff();
        public void changeVolume(int volume);
        public void changeChannel(int channel);
    }
  • 인터페이스에서 변수를 선언하면 컴파일 시 자동으로 아래와 같이 바뀐다. (상수)
    public static final int MAX_VOLUME = 100;
    public static final int MIN_VOLUME = 0;
  • 인터페이스에서 정의된 메소드는 모두 추상 메소드이다. 위에서 선언된 모든 메소드는 컴파일 시에 다음과 같이 자동으로 변경된다.
    public abstract void on();
    public abstract void off();
    public abstract void volume(int value);
    public abstract void channel(int number);

인터페이스 사용하기

인터페이스를 참조하는 클래스 생성하기

검색창에 TV 검색

  • 인터페이스 사용하는 방법
    • 인터페이스는 사용할때 해당 인터페이스를 구현하는 클래스에서 implements 키워드를 이용한다.
    public class LedTV implements TV{
        public void on(){
            System.out.println("켜다");
        }
        public void off(){
            System.out.println("끄다");   
        }
        public void volume(int value){
            System.out.println(value + "로 볼륨조정하다.");  
        }
        public void channel(int number){
            System.out.println(number + "로 채널조정하다.");         
        }
    }
  • 인터페이스가 가지고 있는 메소드를 하나라도 구현하지 않는다면 해당 클래스는 추상클래스가 된다.(추상클래스는 인스턴스를 만들 수 없음)
    public class LedTVExam{
        public static void main(String args[]){
            TV tv = new LedTV();	//인터페이스도 참조변수의 타입이 가능
            tv.on();
            tv.volume(50);
            tv.channel(6);
            tv.off();
        }
    }
  • 참조변수의 타입으로 인터페이스를 사용할 수 있다. 이 경우 인터페이스가 가지고 있는 메소드만 사용할 수 있다.
  • 만약 TV인터페이스를 구현하는 LcdTV를 만들었다면 위의 코드에서 new LedTV부분만 new LcdTV로 변경해도 똑같이 프로그램이 동작할 것다. 동일한 인터페이스를 구현한다는 것은 클래스 사용법이 같다는 것을 의미한다.
  • 클래스는 이러한 인터페이스를 여러개 구현할 수 있다.

인터페이스 실습

public interface Meter {
    public abstract void start();
    public abstract int stop(int distance);
}
public class Taxi implements Meter {
    // Meter인터페이스의 start와 stop메소드를 구현해야 합니다.
    // stop 메서드는 distance*2가 되게
    
    public void start() {
        System.out.println("시작");
    }
    
    public int stop(int distance){
        return distance*2;
        
    }
}
public class MeterExam {
    public static void main(String[]args){
        Taxi taxi = new Taxi();
        boolean a = Meter.class.isInstance(taxi);
        
        if(a!=true){
            System.out.println("Taxi클래스는 Meter인터페이스를 구현해야 합니다.");
        }
        else if(taxi.stop(200)!=400){
            System.out.println("stop(200)의 값은 400이어야 합니다.");
        }
        else{
            System.out.println("정답입니다. [제출]을 누르세요.");
        }
    }
}

인터페이스 default 메소드와 static 메소드

자바 8의 인터페이스는 default키워드를 이용하여 메소드 구현이 가능

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();
            cal.plus(1, 2);
            int value = cal.exec(5, 10);
            System.out.println(value);
        }
    }
  • 원래 인터페이스가 변경이 되면, 인터페이스를 구현하는 모든 클래스들이 해당 메소드를 구현해야 하는 문제가 있는데 이를 해결하기 위하여 인터페이스에 메소드를 구현해 놓을 수 있도록 하였다.

static 메소드

    public interface Calculator {
        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 value2 = Calculator.exec2(5, 10);  //static메소드 호출. 
            System.out.println(value2);
        }
    }
  • 인터페이스에 static 메소드를 선언함으로써, 인터페이스를 이용하여 간단한 기능을 가지는 유틸리티성 인터페이스를 만들 수 있게 되었다.
  • 사용하는 공식 : 인터페이스명.메소드명

인터페이스 default 메소드 실습

public interface Meter{
    public void start();
    public int stop(int distance);
    
    public default void afterMidnight(){
        System.out.println("자정이 넘었습니다. 할증이 필요한경우 이 메소드를 오버라이드 하세요.");
    }
}
public class Taxi implements Meter{
    public void start(){
        System.out.println("택시가 출발합니다.");
    }
    
    public int stop(int distance){
        int fare = distance * 2;
        System.out.println("택시가 도착했습니다. 요금은 "+fare+"입니다.");
        return fare;
    } 
    
    // 코드를 입력하지 않아도 되지만 오버라이딩한 코드
    public void afterMidnight(){
      System.out.println("자정이 넘었습니다. 할증이 필요합니다.");
    }
    
}
public class TaxiExam{
    public static void main(String[] args){
        Taxi taxi = new Taxi();
        
        taxi.start();
        taxi.afterMidnight();
        taxi.stop(10);
    } 
}
profile
좋았다면 추억이고 나빴다면 경험이다.🍀

0개의 댓글

관련 채용 정보