Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

C#: Method Hiding

If sub Class method has same signature as super class method, then sub class method hides the super class method. If you come from java background, it is quite different (To achieve run time polymorphism (or) method overriding, you need to use virtual keyword).

Program.cs
using System;

class A
{
public void print()
{
Console.WriteLine("I am in A");
}
}

class B : A
{
public void print()
{
Console.WriteLine("I am in B");
}
}

class Program
{
static void Main(string[] args)
{
B b= new B();
b.print();
}
}

Output
I am in B


Following example is for the guys, who come from Java background.

Which method is called, when my sub class instance points to super class variable?
A a= new B();
a.print();    // Calls super class print method

If you are from Java, you definitely say, sub class method is called (Refer method overriding). But in C#, super class print method is called. To achieve run time polymorphism, you need to use the ‘virtual’ keyword. I will explain this in later post.

Program.cs
using System;

class A
{
public void print()
{
Console.WriteLine("I am in A");
}
}

class B : A
{
public void print()
{
Console.WriteLine("I am in B");
}
}

class Program
{
static void Main(string[] args)
{
A a= new B();
a.print();
}
}

Output
I am in A






Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

C#: Method Hiding

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×