C# 기초다지기 - 상속




안녕하세요 열코입니다.

이번시간에는 C# 상속에 대해 알아보도록하겠습니다.

상속은 객체지향 프로그래밍에서 가장 중요한 개념으로, 클래스를 다른 클래스로 정의할 수 있으며

프로그램을 쉽게 만들고 유지관리를 할 수 있습니다.

또한 코드 재사용을 하여 구현시간을 단축할 수 있습니다.


클래스의 상속

클래스를 만들때 완전히 새로운 데이터 멤버 및 함수를 작성하는 대신 프로그래머는 새 클래스가 기존 클래스의

멤버를 상속해야할때 클래스를 상속할 수 있습니다. 기존 클래스를 기본(상위)클래스라고 하며 상속받은 새 클래스를

파생(하위)클래스라고 합니다.

상속의 개념은 is-a 관계를 구현합니다.

예를들어, 포유류 is a 동물, 개 is a 포유류이며 따라서 개 is a 동물이 될 수 있습니다.

 클래스의 상속은 :(콜론)을 이용하여 상속합니다.


기본클래스와 파생클래스

클래스는 하나 이상의 클래스 또는 인터페이스에서 파생(상속)될 수 있습니다.

여러 클래스 또는 인터페이스에서 데이터와 함수를 상속받을 수 있습니다.

예를들어 C#에서 기본 클래스 Shape에서 파생 클래스 Rectangle 예제입니다.

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
using System;
 
namespace InheritanceApplication {
    class Shpae {
        protected int width;
        protected int height;
 
        public void setWidth(int w) {
            width = w;
        }
        public void setHeight(int h) {
            height = h;
        }
    }
 
    class Rectangle : Shape {
        public int getArea() {
            return (width * height);
        }
    }
 
    class Inheritance {
        static void Main(string[] args) {
            Rectangle rect = new Rectangle();
 
            rect.setWidth(3);
            rect.setHeight(5);
 
            Console.WriteLine("AREA : {0}", rect.getArea());
        }
    }
}
cs


기본 클래스 초기화

파생 클래스는 기본 클래스 멤버 변수와 함수를 상속합니다.

기본 클래스 객체는 파생 클래스가 만들어지기 전에 만들어야합니다.

멤버 초기화 목록에서 기본 클래스 초기화는 base 함수를 사용하여 초기화합니다.

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
using System;
 
namespace RectangleApplication {
   class Rectangle {
      
      //member variables
      protected double length;
      protected double width;
      
      public Rectangle(double l, double w) {
         length = l;
         width = w;
      }
      public double GetArea() {
         return length * width;
      }
      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }//end class Rectangle  
   class Tabletop : Rectangle {
      private double cost;
      public Tabletop(double l, double w) : base(l, w) { }
      
      public double GetCost() {
         double cost;
         cost = GetArea() * 70;
         return cost;
      }
      public void Display() {
         base.Display();
         Console.WriteLine("Cost: {0}", GetCost());
      }
   }
   class ExecuteRectangle {
      static void Main(string[] args) {
         Tabletop t = new Tabletop(4.57.5);
         t.Display();
         Console.ReadLine();
      }
   }
}
cs



C#의 다중 상속

C#에서는 다중 상속을 지원하지 않지만 인터페이스를 통해 다중 상속을 구현할 수 있습니다.

다음 예제는 인터페이스로 다중 상속을 구현하는 예제입니다.

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
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;
   }
 
   // Base class PaintCost
   public interface PaintCost {
      int getCost(int area);
   }
   
   // Derived class
   class Rectangle : Shape, PaintCost {
      public int getArea() {
         return (width * height);
      }
      public int getCost(int area) {
         return area * 70;
      }
   }
   class RectangleTester {
      static void Main(string[] args) {
         Rectangle Rect = new Rectangle();
         int area;
         
         Rect.setWidth(5);
         Rect.setHeight(7);
         area = Rect.getArea();
         
         // Print the area of the object.
         Console.WriteLine("Total area: {0}",  Rect.getArea());
         Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
         Console.ReadKey();
      }
   }
}
cs



이상 'C# 상속'에 대해 알아보았습니다.

질문 사항은 모두 커뮤니티에서 받습니다. -> 커뮤니티 바로가기

메인 페이지로 이동하시면 더 많은 자료를 볼 수 있습니다.


'C#' 카테고리의 다른 글

C# 기초다지기 - 클래스  (0) 2018.11.08
C# 기초다지기 - 구조체  (0) 2018.11.08
C# 기초다지기 - 문자열  (2) 2018.11.07
C# 기초다지기 - 배열  (1) 2018.11.06
C# 기초다지기 - 상수  (0) 2018.11.06
C# 기초다지기 - 캡슐화  (0) 2018.11.05
C# 기초다지기 - 프로그램 구조  (0) 2018.11.05
C# 기초다지기 - 변수  (0) 2018.11.05

to Top