new vs virtual vs override Method

class Base
{

public void Print() { Console.WriteLine(“Base Print”); }

}

class Derived : Base
{

public void Print() { Console.WriteLine(“Derived Print”); }

}

class Program
{

static void Main(string[] args)
{

Base b = new Base();
Derived d = new Derived();
Base e = d;
b.Print(); // Base Print
d.Print(); // Derived Print (부모클래스의 메소드와 같은 이름으로 메소드를 정의하면 부모의 메소드는 숨겨짐)
e.Print(); // Base Print (원래 e는 Derived 객체이나 Base 데이타형이므로 Base의 Print 메소드 호출)

}

}

 

new 메소드 새정의 (위의 코드는 아래와 똑같음. new 키워드를 사용하여 명시적으로 명확하게 적어주도록 함)

 

class Base
{
public void Print() { Console.WriteLine(“Base Print”); }
}
class Derived : Base
{
public new void Print() { Console.WriteLine(“Derived Print”); } // 부모클래스의 Print 메소드는 새로 정의
public void BasePrint() { base.Print(); } // 부모클래스의Print는 여전히 사용 가능
}
class Program
{
static void Main(string[] args)
{
Base b = new Base();
Derived d = new Derived();
Base e = d;
b.Print(); // Base Print
d.Print(); // Derived Print (부모클래스의 메소드와 같은 이름으로 메소드를 새로 정의)
d.BasePrint();
e.Print(); // Base Print (원래 e는 Derived 객체이나 Base 데이타형이므로 Base의 Print 메소드 호출)
}
}

 

virtual – override 메소드 재정의 (Method Overriding) run-time에서 객체의 DataType에 따른 late-binding이 일어남

 

class Base
{
public virtual void Print() { Console.WriteLine(“Base Print”); }
}
class Derived : Base
{
public override void Print() { Console.WriteLine(“Derived Print”); } // 부모클래스의 Print 메소드는 재정의
public void BasePrint() { base.Print(); } // 부모클래스의Print는 여전히 사용 가능
}
class Program
{
static void Main(string[] args)
{
Base b = new Base();
Derived d = new Derived();
Base e = d;
b.Print(); // Base Print
d.Print(); // Derived Print (부모클래스의 메소드와 같은 이름으로 메소드를 재정의)
d.BasePrint();
e.Print(); // Derived Print (원래 e는 Derived 객체이므로 late-binding에 의해서 Derived 의 Print 메소드 호출)
}
}