Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#의 인터페이스와 상속

<시간/>

인터페이스

인터페이스는 인터페이스를 상속하는 모든 클래스가 따라야 하는 구문적 계약으로 정의됩니다. 인터페이스는 구문 계약의 '무엇' 부분을 정의하고 파생 클래스는 구문 계약의 '어떻게' 부분을 정의합니다.

C# 인터페이스의 예를 살펴보겠습니다.

예시

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;

namespace InterfaceApplication {

   public interface ITransactions {
      // interface members
      void showTransaction();
      double getAmount();
   }

   public class Transaction : ITransactions {
      private string tCode;
      private string date;
      private double amount;

      public Transaction() {
         tCode = " ";
         date = " ";
         amount = 0.0;
      }

      public Transaction(string c, string d, double a) {
         tCode = c;
         date = d;
         amount = a;
      }

      public double getAmount() {
         return amount;
      }

      public void showTransaction() {
         Console.WriteLine("Transaction: {0}", tCode);
         Console.WriteLine("Date: {0}", date);
         Console.WriteLine("Amount: {0}", getAmount());
      }
   }

   class Tester {

      static void Main(string[] args) {
         Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
         Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);

         t1.showTransaction();
         t2.showTransaction();
         Console.ReadKey();
      }
   }
}

출력

Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

상속

상속을 통해 다른 클래스의 관점에서 클래스를 정의할 수 있으므로 애플리케이션을 더 쉽게 만들고 유지 관리할 수 있습니다. 이는 또한 코드 기능을 재사용하고 구현 시간을 단축할 수 있는 기회를 제공합니다.

상속의 개념은 IS-A 관계를 구현합니다. 예를 들어, 포유류는 동물이고 개는 포유류이므로 개는 동물이기도 합니다.

다음은 C#에서 상속을 사용하는 방법을 보여주는 예입니다.

예시

using System;

namespace InheritanceApplication {
   class Shape {
      public void setWidth(int w) {
         width = w;
      }

      public void setHeight(int h) {
         height = h;
      }

      protected int width;
      protected int height;
   }

   // Derived class
   class Rectangle: Shape {
      public int getArea() {
         return (width * height);
      }
   }

   class RectangleTester {
      static void Main(string[] args) {
         Rectangle Rect = new Rectangle();
   
         Rect.setWidth(5);
         Rect.setHeight(7);

         // Print the area of the object.
         Console.WriteLine("Total area: {0}", Rect.getArea());
         Console.ReadKey();
      }
   }
}

출력

Total area: 35