본문 바로가기
프로그래밍

2_12. 인터페이스

by BlueOcean&Shark 2019. 1. 27.
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
/*
 인터페이스(interface)
 1)인터페이스 선언
     interface 인터페이스명
     {
         반환형식 메소드명(매개변수,...);
         ....
     }
 2)인터페이스 특징
    - 필드는 사용할 수 없음(이벤트,메소드,프로퍼티만을 멤버로 갖는다)
    - 인터페이스의 모든 멤버(이벤트,메소드,프로퍼티)는 public 이다.
      따라서 접근제한자를 사용하지 않는다.
    - 인터페이스는 구현부(몸통)가 없는 추상멤버를 갖는다.
    - 다중 상속이 가능(클래스와 인터페이스 상속, 인터페이스끼리의 상속, 구조체와 인터페이스간의 상속)
      (클래스끼리는 다중상속이 불가능)
    - 인터페이스이름앞에는 보통 대문자 I를 써준다.
    - 인터페이스의 인스턴스를 만들 수 없다.
 */
 
namespace cshapExTwo15
{
    // 1) 클래스와 인터페이스 상속
    interface IMyInterfaceA
    {
        void output();
    }
    interface IMyInterfaceB
    {
        void print();
    }
    class MyClassA : IMyInterfaceA, IMyInterfaceB
    {
        public void output()
        {
            Console.WriteLine("A");
        }
        public void print()
        {
            Console.WriteLine("B");
        }
    }
 
    // 2) 인터페이스끼리의 상속
    interface IMyInterfaceC
    {
        void output(string str);
    }
    interface IMyInterfaceD : IMyInterfaceC
    {
        void output(string str, int n);
    }
    class MyClassC : IMyInterfaceD
    {
        public void output(string str)
        {
            Console.WriteLine($"C - {str}");
        }
        public void output(string str, int n)
        {
            Console.WriteLine($"D - {str} {n}");
        }
    }
 
    class Program 
    {
        static void Main(string[] args)
        {
            MyClassA mc1 = new MyClassA();
            mc1.output();
            mc1.print();
           
            IMyInterfaceA ia = mc1 as IMyInterfaceA;
            ia.output();
 
            IMyInterfaceB ib = mc1;
            ib.print();
 
            MyClassC mc2 = new MyClassC();
            mc2.output("안녕");
            mc2.output("안녕"4);
        }
 
        
    }
}
 
cs

---------------------------------------------결과창------------------------------------------

A

B

A

B

C - 안녕

D - 안녕 4

'프로그래밍' 카테고리의 다른 글

2_14. 프로퍼티  (0) 2019.01.27
2_13. 추상클래스  (0) 2019.01.27
2_11. Tuple(튜플)  (0) 2019.01.22
2_10. struct (구조체)  (0) 2019.01.22
2_9. virtual / override / new  (0) 2019.01.22

댓글