ํด๋์ค๋ฅผ ์์์ด ์ ๋๋๋ก ๋ด์ธํ๋ ๊ฒ์ฒ๋ผ ๋ฉ์๋๋ ์ค๋ฒ๋ผ์ด๋ฉ๋์ง ์๋๋ก
sealed ํค์๋๋ฅผ ์ด์ฉํด์ ๋ด์ธํ ์ ์๋ค.
๊ทธ๋ ๋ค๊ณ ๋ชจ๋ ๋ฉ์๋๋ฅผ ๋ด์ธํ ์ ์๋ ๊ฒ์ ์๋๊ณ ,
virtual๋ก ์ ์ธ๋ ๊ฐ์ ๋ฉ์๋๋ฅผ ์ค๋ฒ๋ผ์ด๋ฉํ ๋ฒ์ ์ ๋ฉ์๋๋ง ๊ฐ๋ฅํ๋ค.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Overriding
{
class Base
{
public virtual void MyMethod()
{
WriteLine("Base.MyMethod()");
}
public virtual void Buy()
{
WriteLine("Base.Buy()");
}
}
class Derived : Base
{
public sealed override void MyMethod()
{
WriteLine("Derived.MyMethod()");
}
public override void Buy()
{
WriteLine("Derived.Buy()");
}
}
class LastDerived : Derived
{
/* //์ปดํ์ผ ์๋ฌ : ์์๋ Derived.MyMethod() ๋ฉค๋ฒ๋ ๋ด์ธ๋์ด ์์ผ๋ฏ๋ก ์ฌ์ ์ํ ์ ์๋ค.
public sealed override void MyMethod()
{
WriteLine("LastDerived.MyMethod()");
}
*/
public override void Buy()
{
WriteLine("LastDerived.Buy()");
}
}
class MainApp
{
static void Main(string[] args)
{
Base baseOrLastDerived = new LastDerived();
baseOrLastDerived.MyMethod(); //Derived.MyMethod()
baseOrLastDerived.Buy(); //LastDerived.Buy()
Derived baseOrDerived = new Derived();
baseOrDerived.MyMethod(); //Derived.MyMethod()
baseOrDerived.Buy(); //Derived.Buy()
LastDerived lastDerived = new LastDerived();
lastDerived.MyMethod(); //Derived.MyMethod()
lastDerived.Buy(); //LastDerived.Buy()
}
}
}
๋ด์ธ ๋ฉ์๋๋ ํ์ ํด๋์ค์ด ์์ฑ์๋ฅผ ์ํ ๊ธฐ๋ฐ ํด๋์ค ์์ฑ์์ ๋ฐฐ๋ ค์ด๋ค.
์ค์๋ ์ํ์ด ์๊ฑฐ๋ ์๋ชป ์ค๋ฒ๋ผ์ด๋ฉํจ์ผ๋ก์จ ๋ฐ์ํ ์ ์๋ ๋ฌธ์ ๊ฐ ์์๋๋ค๋ฉด
๋ด์ธ ๋ฉ์๋๋ฅผ ์ด์ฉํด์ ์์์ ์ฌ์ ์ ๋ง๋ ๊ฒ์ด ๋ซ๋ค.
์ปดํ์ผํ ๋ ์๋ฌ๊ฐ ๋๋ฏ๋ก ํ์ ํด๋์ค์ ์์ฑ์๋ ์ฝ๋๊ฐ ์ ํ์ผ๋ก ์ถ์๋๊ธฐ ์ ์ ๋ฌธ์ ๋ฅผ ํ์ ํ ์ ์๊ธฐ ๋๋ฌธ์ด๋ค.
virtual๋ก ์ ์ธ๋ ๋ฉ์๋๋ฅผ ์ค๋ฒ๋ผ์ด๋ฉํ ๋ฉ์๋๋ง ๋ด์ธ ๋ฉ์๋๋ก ๋ง๋ค ์ ์๋ ์ด์ :
virtual๋ก ์ ์ธํ๋ค๋๊ฑด ๊ธฐ๋ฐ ํด๋์ค์ ์์ฑ์๊ฐ ํด๋น ๋ฉ์๋๋ฅผ ์ค๋ฒ๋ผ์ด๋ฉํ ์ ์๋๋ก ์ค๋นํ๋ค๋ ์๋ฏธ.
-> ๊ตณ์ด ๋ด์ธํ ์ด์ ๋ ์๋ฏธ๋ ์๋ค.
๋ฌธ์ ๋ ์ค๋ฒ๋ผ์ด๋ฉํ ๋ฉ์๋์ธ๋ฐ
์ค๋ฒ๋ผ์ด๋ฉํ ๋ฉ์๋๋ ํ์ ํด๋์ค์ ํ์ ํด๋์ค์์๋ ์๋์ผ๋ก ์ค๋ฒ๋ผ์ด๋ฉ์ด ๊ฐ๋ฅํ๋ค.
๊ทธ๋์ ์ค๋ฒ๋ผ์ด๋ฉ์ ๋ง์ ์ ์๋ ๋ธ๋ ์ดํฌ์ธ sealed ํ์ ์๊ฐ ํ์ํ ๊ฒ์ด๋ค.
'C# > ์ด๊ฒ์ด C#์ด๋ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
28. ์ค์ฒฉ ํด๋์ค (0) | 2022.02.11 |
---|---|
27. ์ฝ๊ธฐ ์ ์ฉ ํ๋, readonly (0) | 2022.02.11 |
25. ์ค๋ฒ๋ผ์ด๋ฉ๊ณผ ๋คํ์ฑ virtual, override (0) | 2022.02.11 |
24. C# ํ์ ๋ณํ ์ฐ์ฐ์ ์ํ ์ฐ์ฐ์, is์ as (0) | 2022.02.11 |
[์ค๊ฐ์ ๊ฒ] ์ ๊ทผํ์ ์ internal์์ ๊ฐ์ ์ด์ ๋ธ๋ฆฌ๋ (0) | 2022.02.11 |