상속?
캡슐화 및 다형성과 함께 객체 지향 프로그래밍의
세가지 주요 특성 중 하나
다른 클래스에 정의된 동작을 재사용, 확장 및 수정하는 새 클래스를 만들 수 있다.
사용하는 이유?
코드 기능을 재사용, 구현 시간 단축
맴버가 상속되는 클래스를 기본 클래스
해당 맴버를 참조하는 클래스를 파생클래스
단 , 부모가 둘일 수는 없다.
새 클래스를 만들 때 기존 클래스의 필드와 메서드를 재사용
=> 더 쉽게 만들고 유지 관리할 수 있다
protected 접근제어자를 사용하는 주된 이유는,
해당 클래스나 상속받은 다른 클래스에서만 생성자를 호출할 수 있게 제한함으로써,
의도치 않은 인스턴스 생성을 방지하고 객체의 일관성을 유지하기 위해서
상속을 받았다면 부모 클래스의 생성자도 호출됨
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step37
{
internal class Program
{
static void Main(string[] args)
{
Marine marineA = new Marine();
marineA.Init("마린 A", 10);
marineA.damage = 2;
Marine marineB = new Marine();
marineB.Init("마린 B", 10);
marineB.damage = 2;
Medic medic = new Medic();
medic.healValue = 3;
marineB.Attack(marineA);
Console.WriteLine("마린 A의 체력 : {0}",marineA.GetHp());
Console.WriteLine("마린 B의 체력 : {0}",marineB.GetHp());
medic.Heal(marineA);
Console.WriteLine("마린 A의 체력 : {0}", marineA.GetHp());
Console.WriteLine("마린 B의 체력 : {0}", marineB.GetHp());
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Step37
{
internal class TerranUnit : StarcraftUnit
{
protected int hp;
protected int maxHp;
public TerranUnit()
{
Console.WriteLine("TerranUnit 클래스 생성자");
}
public void Init(string name, int maxHp)
{
this.name = name;
this.maxHp = maxHp;
this.hp = this.maxHp;
}
public void Hit(int damage)
{
this.hp -= damage;
Console.WriteLine("{0}이 피해{1}를 받았습니다", this.name, damage);
}
public int GetHp()
{
return this.hp;
}
public void AddHp(int heal)
{
this.hp += heal;
Console.WriteLine("{0}의 체력이 회복 되었습니다", this.name);
if(this.hp >= this.maxHp)
{
this.hp = this.maxHp;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step37
{
internal class StarcraftUnit
{
public string name;
//생성자
public StarcraftUnit()
{
Console.WriteLine("StarcraftUnit 생성자");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step37
{
internal class Marine : TerranUnit
{
public int damage;
public Marine()
{
Console.WriteLine("Marine 클래스 생성자");
}
public void Attack(TerranUnit target)
{
target.Hit(this.damage);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step37
{
internal class Medic : TerranUnit
{
public int healValue;
public Medic()
{
Console.WriteLine("Medic 클래스 생성자");
}
public void Heal(TerranUnit target)
{
target.AddHp(this.healValue);
}
}
}
'Study > C#' 카테고리의 다른 글
[C#] 생성자 연결 (0) | 2024.06.12 |
---|---|
[C#] virtual, override (0) | 2024.06.12 |
[C#] static 한정자 (0) | 2024.06.02 |
[C#] this 키워드 (0) | 2024.05.31 |
[C#] 점연산자 NullReferenceException (0) | 2024.05.30 |