hyeonga_code

Java_50_인터페이스 본문

Java

Java_50_인터페이스

hyeonga 2023. 10. 13. 05:59
반응형


 - Interface_인터페이스 
    - 메소드만 가지고 있는 클래스임을 보장합니다.
    - 추상 메소드의 집합입니다.
            - 실제로 구현된 내용이 없습니다.
        - 코드가 없어도 있다고 가정하고 가져다 사용할 수 있게 돕는 역할입니다.
            - 메소드가 있는 것처럼 Compiler에게 인식시키는 역할입니다.
            - 내용이 없어도 오류를 발생시키지 않습니다.
            - 병렬 개발로 시간을 줄이기 위해 서로의 의존성을 줄이기 위해 필요한 정의입니다.
    - 직접 객체를 생성할 수 없습니다.
        - 인터페이스를 상속 받은 클래스를 생성한 뒤에 클래스 객체를 생성합니다.
    - 다중 상속이 가능합니다.
        - Java에서는 기본적으로 다중 상속이 불가능합니다.
            - 상위 클래스는 하위 클래스를 다중으로 가질 수 있습니다.
            - 하위 클래스는 상위 클래스를 다중으로 가질 수 없습니다.

            interface 인터페이스이름 {
                    // 상수
                    // 추상 메소드
                }

            =====
              class A{}
            class B extends A{
                B() {
                    a = 100;
                }
            }
            class C extends A{
                C() {
                    a = 1;
                }
            }

            // class D extends b, c {} 불가능
            // B 의 a 와 C 의 a 가 다르게 선언되어 있으므로 혼선이 생길 수 있습니다.

    - 메소드는 'public abstract'로 선언해야 합니다.
        - 생략이 가능합니다.
    - 조건
        - 멤버 필드: 상수
        - 메소드 : 추상 메소드
        - 중첩 클래스 : static
    - 각자의 구성원이 가지고 있어야 하는 기능을 리스트업하는 역할입니다.

      - 다운 캐스팅  
            - 상위 메소드를 하위 메소드로 형변환합니다.
            - 하위 메소드의 기능을 모두 사용할 수 있습니다.
      - 업 캐스팅
            - 하위 메소드를 상위 메소드로 형변환합니다.
            - 기능이 상위 메소드에 의해 제한됩니다

=====

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
45
46
47
48
49
50
interface A11{
    
    // 멤버 필드
    public static final int A = 1;
    // 상수 선언
    public static int B = 2;
    public final int C = 3;
    public int D = 4;
    int E = 5;
    // private int F = 6;
    // 오류 : Illegal modifier for the interface field A11.F; 
    //      only public, static & final are permitted
    // 오직 public 만 가능
    
    // 메소드
    public abstract void disp();
    public void disp2();
    void disp3();
    
    // public void disp4() { System.out.println("aaa");
    // 오류 : Abstract methods do not specify a body
    // 오직 추상 메서드만 가능
 
    // private void disp5();
    // 오류 : Illegal modifier for the interface method disp5; 
    //      only public, abstract, default, static and strictfp are permitted
 
    // 중첩 클래스
    class Inner11{};
    
    }
}
 
public class ex0325 {
    public static void main(String[] args) {
        System.out.printf("A11.A : %d \n", A11.A);    // A11.A : 1
        // A11.A = 100;
        // 오류: The final field A11.A cannot be assigned.
        // final , 상수이므로 변경 불가
        
        // A11.B = 100;
        // 오류: The final field A11.B cannot be assigned.
        // interface 안에서 멤버 필드를 생성 시, 무조건 final 로 상수 선언
        
        System.out.printf("A11.C : %d \n", A11.C);    // A11.C : 3
        
        A11.Inner11 ai = new A11.Inner11();
        // interface 안의 클래스 객체 생성 가능
    }
}



 - Java에서의 클래스와 인터페이스 상속 관계
=====

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
45
46
47
class A12{
    // 클래스 생성
}
 
interface B12{
    // 인터페이스 생성
}
 
class C12 extends A12 {
    // 클래스는 클래스를 상속 받을 수 있음
    }
 
class D12 implements B12 {
    // 클래스는 인터페이스를 상속 받아 구현할 수 있음
}
 
class E12 extends A12 implements B12 {
    // 클래스는 클래스와 인터페이스를 동시에 상속 받을 수 있음
}
 
interface F12 extends B12 {
    // 인터페이스는 인터페이스를 상속 받을 수 있음
}
 
interface G12 extends B12, F12 {
    // 인터페이스는 인터페이스를 다중 상속 받을 수 있음
}
 
/* 
interface H12 extends A12 {
    // 인터페이스는 클래스를 상속 받을 수 없음
}
*/
 
class I12 implements B12, F12 {
    // 클래스는 인터페이스를 다중 상속 받을 수 있음
}
 
class J12 extends A12 implements B12, F12 {
    // 클래스는 클래스를 상속 받으며 인터페이스를 다중 상속 받을 수 있음
}
 
public class ex0325 {
    public static void main(String[] args) {
        
    }
}





'basic.interface_ex' 패키지 생성
'Buy.java' interface 생성
=====

1
2
3
4
5
6
7
package basic.interface_ex;
 
public interface Buy {
    // 메소드에 대한 규격만 작성할 수 있습니다.
    
    void buy();    // 본체가 없는 메소드 이름만 명시합니다.
}




'Sell.java' interface 생성
=====

1
2
3
4
5
6
7
package basic.interface_ex;
 
public interface Sell {
    // 메소드에 대한 규격만 작성할 수 있습니다.
 
    void sell();    // 본체가 없는 메소드 이름만 명시합니다.
}



 - interface에 명시한 메소드의 본체를 작성해야합니다.

'Customer.java' 클래스 생성
=====

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package basic.interface_ex;
 
public class Customer implements Buy, Sell {
    /*
    - Customer 클래스는 제약이 없는 상태로 interface를 상속 받아 명시되어있는 메소드를 작성해야 함
     - Customer 오류 : The type Customer must implement the inherited abstract method Buy.buy()
         - 'Add unimlpemented methods' 선택
     */
    
    // interface 'Sell.java'에 명시된 메소드를 작성합니다.
    @Override
    public void sell() {
        System.out.println("Selling");
    }
 
    @Override
    public void buy() {
        System.out.println("Buying");
    }
}




'CustomerApp.java' 클래스 생성
=====

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
package basic.interface_ex;
public class CustomerApp {
    
    public static void main(String[] args) {
        
        Customer cust = new Customer();
        
        cust.buy();
            /*    Buying     */
        cust.sell();
            /*    Selling     */
        
        // Upcasting
        Buy buy = cust;
        buy.buy();        // Buy interface 에서는 sell()을 보장하지 않으므로 리스트에 표시되지 않음
        
        Sell sell = cust;
        sell.sell();    // Sell interface 에서는  buy()을 보장하지 않으므로 리스트에 표시되지 않음
        
        // Downcasting
        if( sell instanceof Customer ) {
            // sell 객체가 Customer의 instance 객체일 경우
            Customer cust2 = (Customer)sell;    // 형변환이 가능합니다.
            cust2.buy();
        }
    }
}






반응형