본문 바로가기
Language/Java

인터페이스(Interface)

by 태윤2 2020. 6. 11.

 인터페이스(Interface)

 

클래스가 아님 => 선언부에 class 가 아닌 inerface 키워드를 사용

인터페이스가 가질수 있는 요소는

1) 상수 (public static final)

2) 추상메서드(pbulic abstract)

    => 생성자나 그 외의 것들은 가질수 없음

 

객체 생성이 불가능

     => 대신, 참조형 타입으로 사용 가능하며, 다형성 활용 가능

서브클래스에서 인터페이스를 상속받을 때는 extends 가 아닌 implements 키워드 사용 다중 상속(구현)이 가능하다

인터페이스끼리 상속할 경우 extends 키워드를 사용하며, 다중 상속 가능

 

강제성 및 통일성 제공(추상메서드보다 강력한 강제성을 부여)

 

< 인터페이스 정의 기본 문법 >

[접근제한자] interface 인터페이스명 {

              // 상수

              // 추상메서드

}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Ex {
 
 
    public static void main(String[] args) {
    // 인스턴스는 손쉬운 모듈교체를 할수있다    
    
    PrintClient pc = new PrintClient();
    pc.setPrinter(new DotPrinter());
    pc.PrintThis("Hello.java");
    
    pc.setPrinter(new LaserPrinter());
    pc.PrintThis("Ex.java");
 
    }
}
 
 
interface Printer {
    abstract public void print(Stirng fileName);
}
 
class LaserPrinter implements Printer{
    public void print(String fileName) {
        System.out.println("LaserPrinter 로 출력" + fileName)
    }
}
 
class DotPrinter implements Printer{
        System.out.println("DotPrinter 로 출력" + fileName)
}
 
interface PrintClient {
    private Printer printer;
 
    public void setPrinter(Printer printer){
        this.printer = printer;
    }
    
    public void printThis(Print print) {
        printer.print(fileName);
    }
 
}
 
cs

 

'Language > Java' 카테고리의 다른 글

Set 인터페이스 - 자료구현(Collection Framework)  (0) 2020.06.17
equals(), toString()  (0) 2020.06.17
상수  (0) 2020.06.11
final 키워드  (0) 2020.06.11
추상메서드(abstract method)  (0) 2020.06.11