자바 추상 클래스와 인터페이스
추상클래스
-추상메소드 Abstract Method
선언부만 가지는 메소드
accessModifer 반환타입 메소드이름(매개변수)
-추상클래스
적어도 하나의 추상메소드를 가지는 클래스
*객체 생성에 사용 불가
*상속에 이용
*참조 변수의 타입으로 사용 가능
인터페이스
public interface 인터페이스이름 [extends superinterface]{
상수
abstract methods
default methods - body 있음
static methods - body 있음
}
accessModifer class 클래스 implements 인터페이스{
body
}
-구현 클래스는 인터페이스의 상수, default method, static method를 상속함
-abstract method를 구현
-interface에 선언한 추상 메소드들도 구현해야 함.
자바 클래스는 부모클래스 하나만 상속할 수 있다. 하지만 인터페이스는 다중 상속이 가능하다.
public interface 하위인터페이스 extends 상위인터페이스1, 상위인터페이스2 { ... }
두 개 이상의 인터페이스를 구현 가능하다.
class Animals implements IBird, IFlay {
@Override
public void eat() {
// TODO Auto-generated method stub
}
@Override
public void travel() {
// TODO Auto-generated method stub
}
}
상속과 구현 동시에 가능하다.
class Animals extends Unit implements IBird {
@Override
public void eat() {
// TODO Auto-generated method stub
}
@Override
public void travel() {
// TODO Auto-generated method stub
}
}
인터페이스 변경
인터페이스는 직접 변경 할 수 없다.
-인터페이스에 추상메소드를 추가하면, 지금까지 해당 인터페이스를 구현한 모든 클래스는 이를 구현해야 한다.
변경 방법 1 : 인터페이스 확장(상속)을 통해 변경
public interface newOne extends oriOne{
//새로운 메소드 추가
}
→oriOne을 구현한 기존 클래스는 여전히 작동함, 새로운 구현 클래스는 newOne, oriOne를 선택 가능
(기존 구현 클래스에 영향을 주지 않고 interface 확장 가능)
변경 방법 2 : 기존 인터페이스에 새로운 default method를 추가
기존 구현 클래스 그대로 사용 가능
1. 상속한 default method를 그대로 두거나 재정의 가능
2. abstract method로 재선언 할 수 있음