본문 바로가기
c# 입문

[c#] 다운 캐스팅, 오버라이딩, base

by javaman 2022. 7. 17.

다운 캐스팅

 

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();
        }

    }