다운 캐스팅
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharp2
{
class Player
{
public int hp;
public int attack;
public Player(int hp, int attack)
{
this.hp = hp;
this.attack = attack;
}
}
class Mage : Player
{
public Mage() : base(10, 100)
{
}
}
class Temp
{
public static void Main(string[] args)
{
Player player = new Mage();
Mage mage = player as Mage;
//player의 인스턴스 타입이 Mage이면 다운 캐스팅
/* if (player is Mage)
{
Mage mage = (Mage)player;
}*/
}
}
}
메서드 오버라이딩 overriding
public virtual void move(); //부모 클래스 메서드
public override void move();//자식 클래스 메서드
//override != overload
부모 클래스 메서드 접근
base -> 부모 클래스의 생성자에 접근하는 키워드
namespace CSharp2
{
class Player
{
public int hp;
public int attack;
public Player(int hp, int attack)
{
this.hp = hp;
this.attack = attack;
}
public virtual void move()
{
Console.WriteLine("플레이어가 움직입니다");
}
}
class Mage : Player
{
public Mage() : base(10, 100)
{
}
public override void move()
{
base.move();
}
}
'c# 입문' 카테고리의 다른 글
[c#] 제네릭 타입, 프로퍼티 (0) | 2022.07.17 |
---|---|
[c#] 배열, List, Dictionary (0) | 2022.07.17 |
[c#] c# 상속성 (0) | 2022.07.09 |
[c#] CSharp this 키워드, static키워드 (0) | 2022.07.09 |
[c#] 복사(copy)타입 변수와 참조(ref)타입 변수 (0) | 2022.07.09 |