Showing posts with label Inheritance. Show all posts
Showing posts with label Inheritance. Show all posts

Overview of inheritance with C# : part 2

Overriding

If we create base class method to virtual and override the method of the derived class, now when we instantiate the base class object to derived class and call the method with respect to the object then method of derived class will be invoked.

Sample Code

Overview of inheritance with C# : part 1

When base class and derived class both have same method but base class's method is not virtual, and derived class's method is not overridden, then if we instantiate the object of base class to derived class and call the method with respect to the object created, the method written in base class will be invoked.

Sample code

namespace Inheritance { class Program { static void Main(string[] args) { BaseDemo bd = new DerivedDemo(); bd.PrintString(); Console.ReadLine(); } } class BaseDemo { public BaseDemo() { } public void PrintString() { Console.WriteLine("Base Demo Invoked"); } } class DerivedDemo : BaseDemo { public DerivedDemo() { } public void PrintString() { Console.WriteLine("Derived Demo Invoked"); } } }
Output
Base Demo Invoked

Compilation of above code will generate warning that
"Warning 1 'Inheritance.DerivedDemo.PrintString()' hides inherited member Inheritance.BaseDemo.PrintString()'. Use the new keyword if hiding was intended."