C# Abstract class and method
C# abstract class and method
Abstract Class
In C#, we cannot create objects of an abstract class. We use the abstract
keyword to create an abstract class. For example,
// create an abstract class
abstract class Language {
// fields and methods
}
...
// try to create an object Language
// throws an error
Language obj = new Language();
Inheriting Abstract Class
As we cannot create objects of an abstract class, we must create a derived class from it. So that we can access members of the abstract class using the object of the derived class. For example,
using System;
class Program
{
static void Main(string[] args)
{
//wrong
//Animal obj = new Animal();
//Parent reference, child object - possible
Animal obj = new Dog();
Console.ReadLine();
}
}
// abstract base class
abstract class Animal
{
protected void eat()
{
Console.WriteLine("I can eat...");
}
}
//concrete derived class
class Dog : Animal
{
}
C# Abstract Method
A method that does not have a body is known as an abstract method. We use the abstract
keyword to create abstract methods. For example,
public abstract void makeSound();
Here, makeSound()
is an abstract method. An abstract method can only be present inside an abstract class. When a non-abstract class inherits an abstract class, it should provide an implementation of the abstract methods.
Example: Implementation of the abstract method
using System;
abstract class Animal
{
// abstract method
public abstract void makeSound();
}
// inheriting from abstract class
class Dog : Animal
{
// provide implementation of abstract method
public override void makeSound()
{
Console.WriteLine("Bark Bark");
}
}
class Program
{
static void Main(string[] args)
{
// create an object of Dog class
Dog obj = new Dog();
obj.makeSound();
Console.ReadLine();
}
}
In the above example, we have created an abstract class named Animal
. We have an abstract method makeSound()
inside the class. We have a Dog
class that inherits from the Animal
class. Dog
class provides the implementation of the abstract method makeSound()
.
Notice, we have used override
with the makeSound()
method. This indicates the method is overriding the method from the base class. We then used the object of the Dog
class to access makeSound()
. If the Dog
class had not provided the implementation of the abstract method makeSound()
, Dog
class should have been marked abstract as well.
Last updated