Java/Java icia 19일차

인터페이스 ( interface ) 에 대해

swkn 2023. 3. 20. 11:21

인터페이스 ( interface ) 란 ?

공통 메소드를 추상화한 클래스

 

 

1 . 추상메소드 ( abstract method )

- 실행 블록은 정의되어 있지 않고 리턴타입 , 이름 , 매개 변수만 정의

인터페이스를 선언할 때에는

public interface Interface1 {

}

interface라는 용어를 써서 선언을 한다.

 

public interface BoardRepository {
	public boolean save(BoardDTO boardDTO);
    
 }

메소드에 save에는 실행블록이 없다.

이러면 실제 동작은 구현 클래스 (  implements class ) 에서 하게 된다.

2. 구현 클래스 (  implements class )

인터페이스에서 정의한 추상메소드에 대한 실행 블록을 정의한다.

상속을 받은 것처럼 재정의 하는 형태 ( 리턴타입 , 이름 매개변수 수정 불가 )

public interface interface1 {
	public void method1();
}

public class Impl1 implements interface1 {
	public void method1() {
 // 실행 내용을 작성
 	}
 }

 

구현하는 클래스는 인터페이스에서 정의한 추상메소드에 대한 실행내용을 반드시 작성해야 한다.

 

상속과 구현클래스의 차이에는

상속받았을때 메소드는 선택적으로 재정의하지만 , 구현클래스는 무조건적으로 구현해야한다.

 

3. 인터페이스의 특징

인터페이스 자체를 인스턴스화 ( 객체화 ) 할 수 없다.

public Interface Interface1 {

}

public class InterfaceMain {
	public static void main(String[] args) {
    	interface1 int1 = new Interface1(); // => X
    }
}

좌변은 인터페이스 타입 우변은 해당 인터페이스를 구현한 클래스의 생성자

Impl1 , Impl2 클래스는 interface1을 구현한 클래스라면

Interface1 int1 = new Impl1();
Interface1 int1 = new Impl2(); // => O

 

ChildClass c2 = new ParentClass(); =>에러  // 자동형변환때 큰쪽에서 작은쪽 안되는것처럼 같은 개념
ParentClass p2 = new ChildClass();

부모클래스가 자식클래스에 형변환 될수 없다.