Records rather than Memories

인터페이스(interface) 본문

Software/JAVA

인터페이스(interface)

Downer 2019. 10. 23. 19:10
1
2
3
4
5
6
7
8
9
package org.opentutorials.javatutorials.interfaces.example1;
 
interface I{
    public void z();
}
 
class A implements I{
    public void z(){}
}
c

개념적 설명

인터페이스 I안에는 z()라는 메소드가 존재하지만 본체(중괄호)가 존재하지 않는다.

class A implements I{ }라고 하면 인터페이스를 구현하는 것이라고 생각하면 된다.

만약 이 부분없이 컴파일하면 오류가 나온다.

 

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

 

- 메소드 z()를 강제로 구현하는 것이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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());
    }
}
cs

계산기 개발과 사용법 작업을 개발자 A, B 두명이서 진행한다고 생각하자. 개발자 A가 개발자 B 작업이 완성될 때까지 기다리면 자신은 진행할 수 없기 때문에 CalculatorDummy라는 모조 클래스를 만들어 놓으면 개발자 B의 로직이 잘 만들어져 3개월 뒤 인계될 것이라고 기대하고 자신이 할 구현을 진행한다.

 

그런데 시간이 지나고 계산기 개발자가 해당 클래스를 보니 세 개의 값이 아니라 두 개의 값을 이용한다고 가정하면 호환이 되지 않을 수 있다.

 

따라서 커뮤니케이션 미스가 일어나지 않도록 자바 기능으로 약속을 지정하면 안정적으로 작업을 진행할 수 있다. 그것이 바로 인터페이스(interface).

 

 

1
2
3
4
5
6
7
package org.opentutorials.javatutorials.interfaces.example2;
 
public interface Calculatable {
    public void setOprands(int first, int second, int third) ;
    public int sum(); 
    public int avg();
}
cs

위 약속을 정의하는 인터페이스를 이용해 동일한 메소드를 만들도록 규약을 지켜 공유하면 각자 구현하는 방식에 영향을 덜 받으며 혐업을 할 수 있다.

 

 

'Software > JAVA' 카테고리의 다른 글

재귀함수를 이용한 자바 프로그래밍  (0) 2019.11.06
generic이란?  (0) 2019.10.24
final  (0) 2019.10.23
abstract  (0) 2019.10.23
접근 제어자  (0) 2019.10.23
Comments