C#

[class] C# - interface (인터페이스) ★

3,167
목차
  1. interface 예제 - 단일 interface 구현
  2. interface 정의
  3. interface 예제 - 다중 interface 구현

 

interface 예제 - 단일 interface 구현

파일명: Program.cs

 

using System;

namespace Homzzang

{

    interface Site

    {

        void site();

        void host();

    }


    class My : Site

    {

        public void site()

        {

            Console.WriteLine("홈짱닷컴");

        }

        public void host()

        {

            Console.WriteLine("Homzzang.com");

        }

    }


    class Program

    {

        static void Main(string[] args)

        {

            My my = new My();

            my.site();

            my.host();

        }

    }

}


결과값:

홈짱닷컴

Homzzang.com

 

interface 정의

 

추상 (메서드・속성)만 포함하는 특수한 유형의 클래스 선언에 사용.

※ 첫 글자는 대문자 사용. 

 


 

1. 클래스 vs 인터페이스

 

class (클래스) :

  • 콜론( : ) 키워드 사용해 상속.
  • 클래스가 오직 1개의 클래스만 상속 가능. (※ 다중 상속 지원 X)

 

interface (인터페이스) :

  • 콜론( : ) 키워드 사용해 구현.
  • 클래스가 복수의 인터페이스를 구현 가능. (※ 다중 구현 지원 O)
  • 쉼표( , ) 이용해 인터페이스를 나열.

 

2. 인터페이스 특징

  • 추상 클래스와 마찬가지로, 직접 객체 생성 불가.
  • 선언된 메서드・속성의 구체적 정의는 구현 클래스에서 함.
  • 인터페이스 구현 시, 반드시 선언된 메서드를 정의해줘야 함.
  • 인터페이스는 (메서드・속성)은 포함하나, 필드/변수는 포함 X .
  • 인터페이스 메서드・속성은 기본적으로 abstract, public 임.
  • 인터페이스는 생성자 가질 수 없음. (∵ 객체 생성 불가하므로.)
  • 첫 글자는 대문자 사용 권장.

 

3. 인터페이스 사용 이유

  • 보안 확보. (∵ 특정 세부 정보 숨기고, 주요 정보만 표시)
  • 코드 정합성 확보. (즉, 코드 복잡성에 따른 에러 발생 방지)

 

 

interface 예제 - 다중 interface 구현

파일명: Program.cs

 

using System;

namespace Homzzang

{

    interface Site

    {

        void site();

    }

    interface Host

    {

        void host();

    }

    class My : Site, Host

    {

        public void site()

        {

            Console.WriteLine("홈짱닷컴");

        }

        public void host()

        {

            Console.WriteLine("Homzzang.com");

        }

    }


    class Program

    {

        static void Main(string[] args)

        {

            My my = new My();

            my.site();

            my.host();

        }

    }

}


결과값:

홈짱닷컴

Homzzang.com



분류 제목
basic C# - Switch (스위치 조건문)
basic C# - While Loop (와일 반복문)
basic C# - For Loop (포 반복문)
basic C# - Break/Continue (브레이크/컨티뉴) 키워드 - 반복문 빠져나가기 / 특정 조건 건너띄기
basic C# - Arrays (배열)
method C# - Methods (메서드) - 정의/호출
method C# - Method Parameters (메서드 매개변수)
method C# - Method Overloading (메서드 오버로딩)
class C# - OOP (객체 지향 프로그래밍)
class C# - Class (클래스) / Object (객체)
class C# - Class Members (클래스 멤버) - 속성(=필드), 메서드
class C# - Constructors (생성자)
class C# - Access Modifiers (접근 수정자)
class C# - Encapsulation (캡슐화) ※ Getter (게터) / Setter (세터)
class C# - Inheritance (상속)
2/3
목록
 홈  PC버전 로그인 일본어
그누앞단언어
그누뒷단언어
그외코딩언어
그누보드
제작의뢰
Q&A
커뮤니티 2
웹유틸
회원센터
홈짱닷컴 PC버전 로그인