7.10.1 인터페이스(interface)
- 일반 메서드 및 멤버 변수를 가질 수 없는 클래스. 추상만 가질 수 있다.
- 다른 클래스 작성에 도움을 줄 목적으로 만듦
- class의 Object처럼 최고 조상은 없다
7.10.2 인터페이스 작성
- class대신 interface를 사용
- public or default 접근 제어자 사용
interface A{}
- 모든 멤버 변수는 public static final 이어야 하며, 생략 가능
- 모든 메서드는 public abstract 이어야 하며, 생략 가능
interface Card{
public static final int SPACE = 4;
public int DIAMOND = 3; //public static final int DIAMOND
static int HEART = 2; //public static final int HEART
final int CLOVER = 1; //public static final int CLOVER
public abstract String getCardNumber();
String getCardKind(); //public abstract String getCardKind
}
7.10.3 인터페이스 상속
- 다중상속 가능
interface Fightable extends Movable, Attackable{}
7.10.4 인터페이스 구현
- 추상 클래스와 마찬가지로 인터페이스 자체로 인스턴스 생성 불가
class Fighter implements Fightable{}
- 상위 interface의 일부만 구현을 하려면 abstract class로 선언
interface Fightable{
void a();
void b();
}
abstract class Test implements Fightable{
void a(){}
}
//Error
class Test implements Fightable{
void a(){}
}
/*
Fightable의 b 메서드를 구현안해서 컴파일 에러
*/
7.10.5 인터페이스를 이용한 다중상속
- 두 부모 클래스 중에서 비중이 높은 쪽을 선택하고 다른 한쪽은 클래스 내부에 멤버변수를 포함하는 방식으로 처리(abstaract의 클래스 다중상속 구현방식과 동일)
- 어느 한쪽의 필요한 부분을 뽑아서 인터페이스로 만든 다음 구현
public class TVCR extends Tv implements IVCR{
VCR vcr = new VCR();
public viod play(){
vcr.play();
}
}
7.10.6 인터페이스를 이용한 다형성
- 부모의 참조변수에 자식의 인스턴스를 할당할 수 있는 성질 이용
class Fighter extends Unit implements Fightable{
public void attact(Fightable f){}
}
- 리턴타입이 인터페이스라는것은 메서드가 해당 인터페이스를 구현한 클래스의 인스턴스를 반환하는 것
Fightable method(){
return new Fightable();
}
Parseable parser = ParseManager.getParser("XML");
public static Parseable getParser(String type){
if(type.equals("XML")){
return new XMLParser();
}
}
7.10.7 인터페이스의 장점
- 개발시간 단축
- 표준화
- 클래스간의 관계를 맺어줄 수 있음
- 독립적인 프로그래밍 가능
class A{
void aTest(I i){
i.play();
}
}
interface I{
public abstract void play();
}
class B implements I{
public void play(){
Sysytem.out.println("b");
}
}
public Test{
public static void main(String[] args){
A a = new A();
a.aTest(new B());
}
}
7.10.8 default 메서드와 static 메서드
- JDK1.8 이후 interface에 default 메서드와 static 메서드 생성가능
- default method
- 추상 메서드가 아니므로 구현할 의무x
interface A{ void method(); //구현의무o default void method2(); //구현의무x }
- 여러 인터페이스의 default 충돌시 오버라이딩을 사용
- 조상의 메서드와 자식의 default 이름 충돌시, 조상의 메서드를 상속받고 자식의 default무시
- static 메서드
- static을 붙인 메서드
'자바의 정석 정리' 카테고리의 다른 글
자바의 정석 - 8.1 프로그램 에러 (0) | 2022.06.17 |
---|---|
자바의 정석 - 7.11 내부 클래스 (0) | 2022.06.13 |
자바의 정석 - 7.9 추상 클래스 (0) | 2022.06.13 |
자바의 정석 - 7.8 다형성 (0) | 2022.06.13 |
자바의 정석 - 7.7 제어자 (0) | 2022.06.13 |