Sunday, 4 November 2012

Program to show the use of sealed keyword on methods in inheritance and overriding


using System;
class GrandParent
{
 private string clname;
 public GrandParent(){}
 public GrandParent(string s)
 {
  clname = s;
 }
 public virtual void Display()
 {
  Console.WriteLine("GrandParent Class Display Method called by "+clname+"\'s object");
 }
}
class Parent : GrandParent
{
 private string clname;
 public Parent(){}
 public Parent(string s):base(s)
 {
  clname = s;
 }
 public sealed override void Display()
 {
  Console.WriteLine("Parent Class Display Method called by "+clname+"\'s object");
  base.Display();
 }
}
class Child : Parent
{
 public Child(string s):base(s){}
 /*public override void Display()            //Error ; inherited method cannot be override b'coz it is sealed
  {
   Console.WriteLine("Child Class Method");
   base.Display();
  }*/
 public void Show()
 {
  Console.WriteLine("Child Class Show Method called");
  Display();
 }
}
class HideTest
{
 static void Main()
 {
  GrandParent g=new GrandParent("GrandParent");
  Parent p=new Parent("Parent");
  Child d=new Child("Child");
  g.Display();
  p.Display();
  d.Show();
  Console.ReadKey();
 }
}

Output:-

No comments:

Post a Comment