C# Program to Demonstrate Method Hiding
Posted by Superadmin on August 14 2022 03:59:56

C# Program to Demonstrate Method Hiding

 

This is a C# Program illustrate method hiding.

Problem Description

This C# Program Illustrates Method Hiding.

Problem Solution

Here a method func() in the base class and in the derived class give a completely new definition to the same method by preceding it with ‘new’ keyword

Program/Source Code

Here is source code of the C# Program Illustrate Method Hiding. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program Illustrate Method Hiding
 */
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
    public class Demo
    {
        public virtual double Area(double r)
        {
            return r * r;
        }
        public void func()
        {
            Console.WriteLine("Base Class");
        }
    }
    public class A : Demo
    {
        public override double Area(double r)
        {
 
            return base.Area(r) * r;
        }
        public new void func()
        {
            Console.WriteLine("Derived Class");
        }
    }
    public class Test
    {
        public static void Main(string[] args)
        {
            A o1 = new A();
            Console.WriteLine(o1.Area(20));
            o1.func();
            Console.ReadLine();
        }
    }
}
Program Explanation

In this C# program, using new keyword we are creating an object ‘o1’ variable for class A. The method func() in the base class and in the derived class give a completely new definition to the same method by preceding it with ‘new’ keyword.

 

In Demo class we have created two functions. The Area() function is used for computing an area. Then func() function is used to print the output of the program. Then ‘class A’ inherits the property of Demo class, then compute the area.

Runtime Test Cases
 
8000
Derived Class