C# 클래스 - 상속

C# 2016. 6. 8. 01:17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Parent
{
    int property;
    public virtual void foo()
    {
        System.Console.WriteLine("Foo!");
    }
}
 
public class Child : Parent
{
    public override void foo()
    {
        // 부모의 foo 호출
        base.foo();
 
        // 아래 두 줄은 같은 동작
        this.foo();
        foo();
    }
}


virtual 키워드를 붙이지 않은 메소드는 override 할 수 없다.


부모 함수를 찾고 싶으면 base 키워드를 이용한다.

(C++에서의 Parent::foo() 와 같다.)


1
2
3
4
5
6
7
8
9
public sealed class Leaf
{
 
 
public class ChildLeaf : Leaf // 컴파일 안됨
{
 
}
cs


sealed 키워드를 사용해서 상속을 막을 수 있다.





* C#에서는 다중상속을 지원하지 않는다.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Parent()
{
    int number;
    public Parent(int number)
    {
        this.number = number;
    }
}
 
public class Child : Parent
{
    public Child() // 에러 발생
    {
    }
}
cs


C#에서 위와 같이 부모 클래스에는 없는 signature의 생성자가 있을 경우에, 아래와 같은 문법을 활용할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Parent()
{
    int number;
    public Parent(int number)
    {
        this.number = number;
    }
}
 
public class Child : Parent
{
    public Child() : base(0)
    {
    }
    
    public Child(int number) : base(number) // 이런 것도 된다.
    {
    }
}
cs


부모 자식간에만 되는 것은 아니다. 아래와 같이 활용 가능.

1
2
3
4
5
6
7
8
9
10
11
public class Parent()
{
    int number;
    public Parent(int number)
    {
        this.number = number;
    }
    public Parent() : this(0)
    {
    }
}
cs


아주 좋은 기능이다.

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

C# 연산자 오버로딩  (0) 2016.06.08
C# 클래스 - Object 클래스  (0) 2016.06.08
C# 클래스 - 형변환  (0) 2016.06.08
C# 클래스 - 프로퍼티(property)  (0) 2016.06.07
C# 클래스 - 생성자  (0) 2016.06.07
Posted by RPG만들기XP
,