- An override method provides a new implementation of a member inherited from a base class. The overridden base method must have the same signature as the override method.You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
- Only a procedure (Function or Sub) or property
- Overriding the accessibility is not possible(Base and child class having same access specifiers).
- Overriding element inherited by further derived classes; overridden element still overridden.
- When two programming elements share the same name, one of them can hide, or shadow, the other one. In such a situation, the shadowed element is not available for reference.
- It applied to any declared element type(procedure (Function or Sub) or property and fields).
- Any accessibility is possible.
- Shadowing element inherited by further derived classes; shadowed element still hidden.
class BaseClass
{
public int X = 10;
public virtual string overridingMethod()
{
return "BaseClass overridingMethod \n";
}
public string hidingMethod()
{
return "BaseClass hidingMethod \n";
}
public void ParentDisplay()
{
Console.WriteLine("Paerent " + X);
}
}
class DerivedClass : BaseClass
{
public new string X = "Hai"; //Hiding applied even field also(new keyword used for hiding)
public override string overridingMethod()
{
return "DerivedClass overridingMethod \n";
}
internal new string hidingMethod() //Change of accessibility possible in hiding
{
return "DerivedClass hidingMethod \n";
}
public void childDisplay()
{
Console.WriteLine("Child " + X);
}
}
class MainClass
{
static void Main()
{
BaseClass bc = new BaseClass();
Console.WriteLine("Base class ref assigned to Base class object");
bc.ParentDisplay();
Console.Write(bc.overridingMethod());
Console.Write(bc.hidingMethod());
DerivedClass dc = new DerivedClass();
Console.WriteLine("");
Console.WriteLine("Derived class ref assigned to Derived class object");
dc.ParentDisplay();
dc.childDisplay();
Console.Write(dc.overridingMethod());
Console.Write(dc.hidingMethod());
BaseClass bc2 = new DerivedClass();
Console.WriteLine("");
Console.WriteLine("Base class ref assigned to Derived class object");
bc2.ParentDisplay();
Console.Write(bc2.overridingMethod()); //It will return overrided method(not relavent to it's reference)
Console.Write(bc2.hidingMethod()); //It will return method which is relavent to it's reference
}
}
Output :
Base class ref assigned to Base class object
Parent 10
BaseClass overridingMethod
BaseClass hidingMethod
Derived class ref assigned to Derived class object
Parent 10
Child Hai
DerivedClass overridingMethod
DerivedClass hidingMethod
Base class ref assigned to Derived class object
Parent 10
DerivedClass overridingMethod
BaseClass hidingMethod
No comments:
Post a Comment