Programming/Java

인터페이스(interface)

사랑우주인 2021. 6. 7. 16:07

인터페이스의 역할은?

어떤 객체가 특정한 인터페이스를 사용한다면 그 객체는 반드시 인터페이스의 메서드들을 구현해야 한다. 

만약 인터페이스에서 강제하고 있는 메소드를 구현하지 않으면 이 애플리케이션은 컴파일 조차 되지 않는다.

 

인터페이스와 상속의 차이점은?

상속은 상위 클래스의 기능을 하위 클래스가 물려 받는다.

인터페이스는 하위 클래스에 특정한 메서드가 반드시 존재하도록 강제한다.

package org.opentutorials.javatutorials.interfaces.example1;
 
interface I{
    public void z();
}
 
class A implements I{
    public void z(){}
}

 

클래스 A는 인터페이스 I를 '구현'한다

 

실질적인 쓰임

개발자 A와 B가 계산기 기능이 필요한 프로젝트를 만든다 가정해보자.

A는 계산기 클래스를 만들고, B는 그 클래스를 사용하는 로직을 만든다고 해보자.

이런 경우, 개발자 B는 A가 계산기를 잘 만들어서 나중에 제출할 것이라고 기대하고 개발을 진행할 것이다. 

아래와 같이 B는 가짜 로직을 만들어서 코드를 작성했다.

package org.opentutorials.javatutorials.interfaces.example1;
class CalculatorDummy{
    public void setOprands(int first, int second, int third){}
    public int sum(){
        return 60;
    }
    public int avg(){
        return 20;
    }
}
public class CalculatorConsumer {
    public static void main(String[] args){
        CalculatorDummy c = new CalculatorDummy();
        c.setOprands(10,20,30);
        System.out.println(c.sum()+c.avg());
    }
}

 

하지만 A는 매개변수를 2개라 가정하고 클래스를 만들었다!

package org.opentutorials.javatutorials.interfaces.example1;
 
class Calculator {
    int left, right;
    public void setOprands(int left, int right) {
        this.left = left;
        this.right = right;
    }
    public void sum() {
        System.out.println(this.left + this.right);
    }
    public void avg() {
        System.out.println((this.left + this.right) / 2);
    }
}

 

이러한 문제를 해결하기 위한 가장 좋은 방법은 무엇일까? 협업자 상호 간에 구체적인 약속을 하면 된다. 특히 그 약속을 코드 안에서 할 수 있다면 참 좋을 것이다. 그렇다. 인터페이스가 필요한 순간이다. 

 

 

package org.opentutorials.javatutorials.interfaces.example2;
 
class Calculator implements Calculatable {
    int first, second, third;
    public void setOprands(int first, int second, int third) {
        this.first = first;
        this.second = second;
        this.third = third;
    }
    public int sum() {
        return this.first + this.second + this.third;
    }
    public int avg() {
        return (this.first + this.second + this.third) / 3;
    }
}

 

package org.opentutorials.javatutorials.interfaces.example2;
class CalculatorDummy implements Calculatable{
    public void setOprands(int first, int second, int third){
    }
    public int sum(){
        return 60;
    }
    public int avg(){
        return 20;
    }
}
public class CalculatorConsumer {
    public static void main(String[] args) {
        CalculatorDummy c = new CalculatorDummy();
        c.setOprands(10, 20, 30);
        System.out.println(c.sum()+c.avg());
    }
}

 

인터페이스를 이용해서 서로가 동일한 메서드를 만들도록 규약을 만들어서 공유한 결과,
각자가 상대의 일정이나 구현하는 방식에 덜 영향을 받으면서 애플리케이션을 구축할 수 있었다.

 

인터페이스의 규칙

  • 하나의 클래스가 여러 개의 인터페이스를 구현할 수 있다.

    클래스 A는 메서드 x나 z 중 하나라도 구현하지 않으면 오류가 발생한다.
    package org.opentutorials.javatutorials.interfaces.example3;
     
    interface I1{
        public void x();
    }
     
    interface I2{
        public void z();
    }
     
    class A implements I1, I2{
        public void x(){}
        public void z(){}   
    }​
  • 인터페이스도 상속이 된다.
    package org.opentutorials.javatutorials.interfaces.example3;
     
    interface I3{
        public void x();
    }
     
    interface I4 extends I3{
        public void z();
    }
     
    class B implements I4{
        public void x(){}
        public void z(){}   
    }
  • 인터페이스의 멤버는 반드시 public이다.
    package org.opentutorials.javatutorials.interfaces.example3;
     
    interface I5{
        private void x();
    }

출처

https://opentutorials.org/course/1223/6063