• Home
  • Abstract Class and Method

Abstract Class and Method

Agenda

Abstraction in C#

Abstraction Example in C#

Example:

abstract class Animal

{

public abstract void eat();

public void drink()

{

Console.WriteLine(“Animal used to drink Water”);

}

}

class Tiger : Animal

{

public override void eat()

{

Console.WriteLine(“Tiger used to eat meat”);

}

}

static void Main()

{

Tiger obj = new Tiger();

obj.eat();

obj.drink();

//Animal animal = new Animal(); // Error CS0144 Cannot create an instance of the abstract type or interface ‘Animal

}

abstract class Animal
{
public abstract void eat();
public abstract void run(); //Create later after one run
public void drink()
{
Console.WriteLine("Animal used to drink Water");
}

}

class Tiger : Animal
{
public override void eat()
{
Console.WriteLine("Tiger used to eat meat");
}

public override void run()
{
Console.WriteLine("Tiger used to run fast");
}
}

static void Main()
{

Tiger obj = new Tiger();
obj.eat();
obj.drink();
obj.run();
//Animal animal = new Animal(); // Error CS0144 Cannot create an instance of the abstract type or interface 'Animal'
Console.ReadKey();
}