C# program to demonstrate the concept of method hiding

Here, we are going to learn about the concept of method hiding and its C# implementation.
Submitted by Nidhi, on September 10, 2020

Here we will create two classes Sample and Demo. Then inherit the Sample class into the Demo class. Here we defined method Method2() in both classes. In the derived class Demo, we gave a completely new definition and hide the inherited definition using the new keyword.

Program:

The source code to demonstrate the concept of method Hiding is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate the concept of method Hiding.
using System;

public class Sample
{
    public virtual void Method1()
    {
        Console.WriteLine("Sample: Method1() called");
    }
    public void Method2()
    {
        Console.WriteLine("Sample: Method2() called");
    }
}

public class Demo : Sample
{
    public override void Method1()
    {
        Console.WriteLine("Demo: Method1() called");
    }
    public new void Method2()
    {
        Console.WriteLine("Demo: Method2() called");
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        Demo Ob = new Demo();
        Ob.Method1();
        Ob.Method2();
    }
}

Output:

Demo: Method1() called
Demo: Method2() called
Press any key to continue . . .

Explanation:

In the above program, we created three classes Sample, Demo, and Program. Here we inherited the Sample class into the Demo class and override the Method1() in the Demo class. Here we also defined method Method2() in both classes. In the derived class Demo, we gave a completely new definition and hide the inherited definition using the new keyword.

The Program class contains the Main() method, In the Main() method we created the object Ob of Demo class and then called Method1() and Method2().






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.