class [자식클래스명] : [부모클래스명]
부모인 기준 클래스(Base Class)로부터 상속하여 자식인 파생 클래스(Derived Class)를 만들 수 있다
상속을 하게 되면 부모 클래스의 데이터 및 메서드들을 자식 클래스에서 사용할 수 있다
자식 클래스는 대개 부모로부터 물려받은 자원들 외에 자기 고유의 데이터와 메서드를 추가해서 사용한다
상속은 colon(:)을 사용해 정의하고 단 하나의 부모 클래스만 상속할 수 있다
// 부모 클래스
public class Animal
{
public string Name { get; set; }
public int Age { get; set; }
}
// 자식 클래스
public class Dog : Animal
{
public void HowOld()
{
Console.WriteLine("나이: {0}", this.Age);
}
}
public class Bird : Animal
{
public void Fly()
{
Console.WriteLine("{0}가 날다", this.Name);
}
}
추상 클래스는 구현되지 않은 멤버를 포함하고 있으며 abstract 키워드를 사용한다
구현되지 않은 멤버는 추상 클래스로부터 파생되는 클래스에서 override 키워드를 통해 반드시 그 멤버를 구현해 주어야 한다
추상 클래스는 new를 통한 객체 생성을 할수 없다
// 추상 클래스
public abstract class PureBase
{
public abstract int GetFirst();
public abstract int GetNext();
}
// 파생 클래스
public class DerivedA : PureBase
{
private int no = 1;
// override
public override int GetFirst()
{
return no;
}
public override int GetNext()
{
return ++no;
}
}
객체를 지정된 클래스 타입으로 변환, 실패 시 null을 리턴
명시적 캐스팅(Explicit Casting)은 변환 실패 시 Exception을 발생
특정 클래스 타입이나 인터페이스를 갖고 있는지 확인하는데 사용
class MyBase { }
class MyClass : MyBase { }
class Program
{
static void Main(string[] args)
{
MyClass c = new MyClass();
new Program().Test(c);
}
public void Test(object obj)
{
// as
MyBase a = obj as MyBase;
// is
bool ok = obj is MyBase; //true
// Explicit Casting
MyBase b = (MyBase) obj;
}
}