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,
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,
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,
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
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