Sunday, 4 November 2012

Program of hierarchical inheritance and function overriding


using System;
class BaseClass
{
 public int num1,num2,num3;
 public virtual int function1()
 {
  Console.WriteLine("Base class : function1() returning 1 called.");
  return 1;
 }
 public virtual int function2()
 {
  Console.WriteLine("Base class : function2() returning 2 called.");
  return 2;
 }
 public virtual int function3()
 {
  Console.WriteLine("Base class : function3() returning 3 called.");
  return 3;
 }
 public BaseClass()
 {
  Console.WriteLine("Base class : Constructor called.");
  num1=function1();
  num2=function2();
  num3=num1+num2+function3();
 }
 static int Main()
 {
  Inheritance1 i1=new Inheritance1();
  Inheritance2 i2=new Inheritance2();
  Inheritance3 i3=new Inheritance3();
  Console.WriteLine("The value of num1 = "+i1.num1);
  Console.WriteLine("The value of num2 = "+i2.num2);
  Console.WriteLine("The value of num3 = "+i3.num3);
  Console.ReadKey();
  return 0;
 }
}
class Inheritance1 : BaseClass
{
 public Inheritance1()
 {
  Console.WriteLine("Inherited class 1 : Constructor called.");
 }
 public override int function1()
 {
  Console.WriteLine("Inherited class : function1() returning 10 called.");
  return 10;
 }
}
class Inheritance2 : BaseClass
{
 public Inheritance2()
 {
  Console.WriteLine("Inherited class 2 : Constructor called.");
 }
 public override int function2()
 {
  Console.WriteLine("Inherited class : function2() returning 20 called.");
  return 20;
 }
}
class Inheritance3 : BaseClass
{
 public Inheritance3()
 {
  Console.WriteLine("Inherited class 3 : Constructor called.");
 }
 public override int function3()
 {
  Console.WriteLine("Inherited class : function3() returning 30 called.");
  return 30;
 }
}

Output:-


No comments:

Post a Comment