-
C# polymorphism (2/4) - OverrideC# 2019. 6. 6. 21:06
What is Override?
While Overloading is which additionally defining several methods with same name, Overriding is re-defining method of classes that are in relation of inherit.
Method of parent class is inherited to child class so that it can be used in child class. In other words, reusing already defined method.
At this time, Overriding is not just reusing but re-defining method so that it can carry out other operation.
Unlike Overloading, Overriding should have identical method name. Overriding is implemented by using virtual and override keyword.
Keyword "virtual" and "override"
When overriding method it should be defined by virtual in parent class, override in child class.
According to below example, if there's Child class which is inherited Parent class, public method is automatically inherited.
class Parent
{
public virtual void ParentMethod()
{
Console.WriteLine("parent method");
}
}class Child : Parent{}
Although ParentMethod is not defined in Child class, it can be used by getting inheritted from Parent class.
Child child = new Child();
child.ParentMethod(); // output : "parent method"at this time, if you want ParentMethod to be implemented differently in child class, you can override.
class Child : Parent
{
public override void ParentMethod()
{
Console.WriteLine("Child Method (override)");
}
}When you call relevant method through Child object, the re-defined method is called.
Child child = new Child();
child.ParentMethod(); //output : "child method"note that you cannot override without keyword "virtual".
출처:http://www.mkexdev.net/Article/Content.aspx?parentCategoryID=1&categoryID=5&ID=675
'C#' 카테고리의 다른 글
delegate (0) 2019.06.10 메모리의 특징 이해하기 (0) 2019.06.10 Indexer (0) 2019.06.06 C# polymorphism (1/4) - Overloading (0) 2019.06.05 Params (0) 2019.06.04