인터페이스(interface)란?
인터페이스는 객체의 특정 행동의 특징을 정의하는 간단한 문법이다.
추상메소드와 비교
- 유사점 : 접근 제어자, return type, 메소드 이름만 정의하며 구현체를 선언하지 않는다.
- 차이점1 : parameter가 없으며 메소드만 정의한다.
- 차이점2 :
implements
키워드를 통해 실제로 구현된다.
예제 코드
// paramter 없이 메소드만 정의한다.
interface Flyable {
void fly(int x, int y, int z);
}
class Pigeon implements Flyable {
private int x,y,z;
@Override
public void fly(int x, int y, int z) {
printLocation();
System.out.println("fly");
this.x = x;
this.y = y;
this.z = z;
printLocation();
}
public void printLocation() {
System.out.println("current location {" + x + ", " + y + ", " + z + "}");
}
}
public class Main {
public static void main(String[] args) {
Flyable pigeon = new Pigeon();
pigeon.fly(1,2,3);
}
}
실행 결과
current location {0, 0, 0}
fly
current location {1, 2, 3}
인터페이스의 특징 정리
- 구현하는 객체의 동작에 대한 명세를 정의한다.
- implements 키워드를 통해 구현하므로 다중 상속이 가능하다.
- 메소드의 시그니처만 선언이 가능하다.
'Java' 카테고리의 다른 글
자바 - 2차원 배열 정렬 (오름차순, 내림차순, 다중 조건) (0) | 2023.03.15 |
---|---|
자바 - 날짜와 시간 (0) | 2023.02.20 |
자바 - 객체지향퀴즈 (0) | 2023.02.20 |
자바 - 추상 클래스 (0) | 2023.02.20 |
자바 - 접근 제어자 (0) | 2023.02.20 |
댓글