• Home
  •  Run-time Polymorphism and Importance of base keyword

 Run-time Polymorphism and Importance of base keyword

Agenda

Run-time Polymorphism in C#

Example:

Public class Animal{

//Overridden method

public void eat()

{

Console.WriteLine(“Animal is eating”);

}}

Public class Tiger : Animal{

//Overriding method

public void eat(){

Console.WriteLine(“Tiger is eating”);

}

static void Main() {

Tiger obj = new Tiger();

//This will call the child class version of eat()

obj.eat();

}

} //Output: Tiger is eating

Importance of base keyword in C#

Example:

public class Animal{

public string name=“Elephant”;

}

public class Dog : Animal{

public string name=“Bullet”;

public void printName(){

Console.WriteLine(Name);//prints Name of Dog class

Console.WriteLine(base.Name);//prints Name of Animal class

}

}

static void Main() {

Dog d=new Dog();

d.printName();

}

 public class Animal
{
public Animal() {
Console.WriteLine("Animal Class Constructor");
}

public string name ="Elephant";
//Overridden method
public void eat()
{
Console.WriteLine("Animal is eating");
}
}
public class Tiger : Animal
{
public Tiger() : base()
{
}
/*public Tiger()
{
Console.WriteLine("Tiger Class Constructor");
} */
public string name = "Royal Bengal Tiger";

public void printName()
{
//Console.WriteLine(name);//prints Name of Tiger class
Console.WriteLine(base.name);//prints Name of Animal class

}
//Overriding method
public void eat()
{
Console.WriteLine("Tiger is eating");
}

public void eatParentClass()
{
base.eat();
}
}

Animal animal = new Animal(); //Base class constructor will be called
// animal.eat();
Tiger obj = new Tiger(); //Both Base class and subclass constructor will be called
//This will call the child class version of eat()
obj.eat();
obj.eatParentClass();

obj.printName();