인터페이스는 객체의 사용 방법을 정의한 타입이다. 일종의 추상 클래스로도 볼 수 있는데, 추상 클래스보다 추상화 정도가 높아 오직 추상 메서드와 상수 만을 멤버로 가질 수 있다.
추상 클래스를 부분적으로만 완성된 '미완성 설계도'라고 한다면, 인터페이스는 구현된 것은 없이 밑그림만 그려져 있는 '기본 설계도'라고 할 수 있다. 따라서 그 자체로 사용되기보다는 다른 클래스를 작성하는데 도움을 줄 목적으로 사용한다.
https://limkydev.tistory.com/197?category=957527
[JAVA] 자바 인터페이스란?(Interface)_이 글 하나로 박살내자
1. 인터페이스 개념과 역할 인터페이스....이 글하나로 박살내자. (회사에서 존댓말을 많이 쓰기때문에 여기서라도 반말로 글을 써보고 싶음 ㅎ) 인터페이스는 뭘까?? 결론부터 말하면, 극단적으
limkydev.tistory.com
interface Creature {
//void disp() {} 에러. 일반 메소드는 사용 불가
abstract void kind(); //추상 메소드만 가능하다
void breathe(); //abstract 생략 가능
}//interface end
이처럼 일반 메서드는 사용할 수 없고 추상 메서드만 가능하다.
//클래스 입장에서 부모가 클래스 : extends 확장
//클래스 입장에서 부모가 인터페이스 : implements 구현
class Tiger implements Creature {
@Override
public void kind() {
System.out.println("포유류");
}
@Override
public void breathe() {
System.out.println("허파");
}
}//class end
class Salmon implements Creature {
@Override
public void kind() {
System.out.println("어류");
}
@Override
public void breathe() {
System.out.println("아가미");
}
}//class end
상속을 할 때 부모가 클래스이면 extends, 부모가 인터페이스면 implements를 사용한다.
//에러. 인터페이스는 직접 객체 생성 불가능
//Creature creature = new Creature();
//인터페이스에서의 다형성
Creature creature = null;
creature = new Tiger();
creature.kind();
creature.breathe();
creature = new Salmon();
creature.kind();
creature.breathe();
인터페이스는 직접 객체 생성을 할 수 없다.
class Unit {
int currentHP;
int x, y;
}//class end
interface Movable {
void move(int x, int y);
}//interface end
interface Attackable {
void attack(Unit u);
}//interface end
interface Fightable extends Movable, Attackable {
//인터페이스 간의 상속은 다중 상속이 가능하다
}//interface end
인터페이스는 다중 상속이 가능하다.
class Fight extends Unit implements Fightable{
//클래스 간의 상속은 단일 상속만 가능하다
@Override
public void move(int x, int y) {}
@Override
public void attack(Unit u) {}
}//class end
class Tetris extends Unit implements Movable, Attackable {
//클래스 입장에서 클래스는 단일 상속만 가능하고, 인터페이스는 다중 구현이 가능하다
@Override
public void move(int x, int y) {}
@Override
public void attack(Unit u) {}
}//class end
클래스는 단일 상속만 가능한 반면 인터페이스는 다중 상속이 가능한 모습이다.
'웹개발 교육 > Java' 카테고리의 다른 글
[35일] Java (41) - 내부 클래스(중첩 클래스) (0) | 2022.09.15 |
---|---|
[35일] Java (40) - 익명 객체 (0) | 2022.09.15 |
[35일] Java (38) - 추상 클래스 (0) | 2022.09.15 |
[35일] Java (37) - 다형성 (0) | 2022.09.15 |
[35일] Java (36) - super (0) | 2022.09.15 |