C# 강좌 : 제 36강 - 상속
상속(Inheritance)
상속은 부모 클래스 (기본 클래스)의 데이터나 동작을 다시 사용하거나 확장, 재정의하여 자식 클래스 (파생 클래스)에서 새롭게 정의하거나 활용할 수 있습니다.
정적 생성자, 인스턴스 생성자, 종료자는 상속되지 않습니다. public, protected, internal으로 선언된 멤버만 상속할 수 있습니다.
상속은 생성자도 상속하여 사용할 수 있습니다.
부모 클래스의 메서드를 접근할 때 사용하는 base 키워드를 이용하여 상속할 수 있습니다.
생성자를 상속 받아 필드를 추가로 할당할 수 있습니다.
전체 코드
using System;
class Shape
{
public int X, Y = 0;
protected int Width, Height = 0;
public Shape()
{
Console.WriteLine("Shape 클래스");
}
public void Inheritance()
{
Console.WriteLine("상속");
}
}
class Rect : Shape
{
public Rect(int x, int y)
{
X = x;
Y = y;
Width = x + 100;
Height = x + 100;
}
public string Information()
{
base.Inheritance();
return String.Format("{0}, {1}, {2}, {3}", X, Y, Width, Height);
}
}
class Circle : Shape
{
private int Radius;
public Circle(int x, int y)
{
X = x;
Y = y;
Radius = (x + y) / 4;
}
public string Information()
{
base.Inheritance();
return String.Format("{0}, {1}, {2}, {3}, {4}", X, Y, Radius, Width, Height);
}
}부모 클래스인 Shape에서 필드인 X, Y, Width, Height를 상속할 수 있습니다.
자식 클래스인 Rect는 콜론 (:)을 통하여 Shape를 상속받습니다.
부모 클래스에서 사용된 X, Y, Width, Height를 상속받습니다.
자식 클래스인 Circle도 콜론 (:)을 통하여 Shape를 상속받습니다.
부모 클래스에서 선언된 필드를 모두 사용하지 않아도 되며, 추가적인 필드인 Radius를 생성하여 사용할 수 있습니다.
base 키워드를 사용하여 자식 클래스에서 부모 클래스의 메서드에 접근하여 호출 할 수 있습니다.
세부 코드
Rect rect = new Rect(100, 100);
Console.WriteLine(rect.Information());
Circle circle = new Circle(100, 100);
Console.WriteLine(circle.Information());Rect와 Circle 클래스의 Information 메서드를 실행할 경우, 부모 클래스의 Console.WriteLine("Shape 클래스");도 같이 호출되어 실행됩니다.
생성자는 상속이 되지 않지만 new 키워드를 사용하여 객체를 생성 시 부모 클래스의 생성자가 자동으로 호출됩니다.
전체 코드
using System;
class Shape
{
public int X, Y = 0;
protected int Width, Height = 0;
public Shape(int x, int y)
{
X = x;
Y = y;
Width = x + 100;
Height = y + 100;
}
}
class Rect : Shape
{
public Rect(int x, int y) : base(x, y) { }
public string Information()
{
return String.Format("{0}, {1}, {2}, {3}", X, Y, Width, Height);
}
}
class Circle : Shape
{
private int Radius;
public Circle(int x, int y) : base (x, y)
{
X = x + 50;
Y = y + 50;
Radius = (x + y) / 4;
}
public string Information()
{
return String.Format("{0}, {1}, {2}, {3}, {4}", X, Y, Radius, Width, Height);
}
}부모 클래스인 Shape에서 필드인 X, Y, Width, Height를 상속할 수 있습니다.
base(x, y) { } 키워드를 사용하여 상속하며, 생성자를 작성하지 않더라도 동일한 기능을 하는 생성자가 생성됩니다.
자식 클래스인 Rect는 부모 클래스와 동일한 생성자를 상속받습니다.
자식 클래스인 Circle은 X, Y, Raidus를 새로 할당하며, Width와 Height는 상속받습니다.
세부 코드
Rect rect = new Rect(100, 100);
Console.WriteLine(rect.Information());
Circle circle = new Circle(100, 100);
Console.WriteLine(circle.Information());Rect와 Circle 클래스의 Information 메서드를 실행할 경우, rect는 X, Y, Width, Height를 출력합니다.
circle은 X, Y, Radius, Width, Height을 출력합니다.
공유하기
Kakao
Naver
Twitter
LinkedIn
Facebook
댓글 남기기