Java/JAVA의 정석_객체지향
인터페이스를 이용한 다형성
Jenny_yoon
2022. 11. 2. 23:12
728x90
반응형
- 인터페이스 타입 매개변수는 인터페이스 구현한 클래스의 객체만 가능
class Fighter extends Unit impletents Fightable {
public void move(int x, int y) { /*내용생략*/}
public void attack(Fightable f) { /*내용생략*/}
}
Unit u = new Fighter();
Fightable f = new Fighter();
f.move(100,200);
f.attack(new Fighter());
interface Fightable {
void move(int x, int y);
void attack(Fightable f); //Fightable인터페이스를 구현한 클래스의 인스턴스만 가능
}
Fightable인터페이스를 구현한 클래스의 인스턴스만 가능
- 인터페이스를 메서드의 리턴타입으로 지정할 수 있다.
Fightable method(){ //Fightable 인터페이스를 구현한 클래스의 인스턴스를 반환
...
Fighter f = new Fighter();
return f; // return (Fightable)f;가 생략된 것
//위 두문장을 한 문장으로 하면 return new Fighter();
}
자손과 조상 관계이기 때문에 Fightable을 f(Fighter)로 형변환해 반환가능
- ex. 예시
package ch7;
abstract class Unit6 {
int x,y;
abstract void move(int x, int y);
void stop() {System.out.println("멈춥니다.");}
}
interface Fightable { //interface의 모든 메서드는 public abstract
void move(int x, int y); //public abstract가 생략됨
void attack(Fightable f); //public abstract 가 생략됨
}
class Fighter extends Unit6 implements Fightable {
public void move(int x, int y) {
//오버라이딩 규칙: 조상(public)보다 접근제어자가 범위가 좁으면 안된다.
System.out.println("["+x+","+y+"]로 이동");
}
public void attack(Fightable f) {
System.out.println(f+"를 공격");
}
Fightable getFightable() { //싸울 수 있는 상대를 불러온다.
Fighter f = new Fighter(); //Fighter를 생성해서 반환
return f; //(Fightable)f 가 생략됨
}
}
public class Ex7_35 {
public static void main(String[] args) {
Fighter f = new Fighter(); //Fighter 대신 Unit(or Fightable)으로 호출가능,but Unit으로 attack호출불
//Fightable(or Fighter로 형변환)이 인터페이스를 구현했으므로 반환가능.
//반환타입이 Fightable일때는 Fightable인터페이스를 구현한 객체를 반환한다.
Fightable f2 = f.getFightable();
// f.move(100, 200);
// f.attack(new Fighter());
}
}
인터스페이스 장점
- 두 대상(객체)간의 '연결, 대화, 소통'을 돕는 '중간역할'을 한다.
- 선언(설계)와 구현을 분리시킬 수 있게 한다.
- 인터페이스 덕분에 B가 변경되어도 A는 안바꿀 수 있게 된다.(느슨한 결합 : (변경에 유리))
- 개발시간을 단축
- 변경에 유리한 유연한 설계 가능
- 서로 관계없는 클래스들을 관계 맺어줌
728x90
반응형