In C#, an abstract class is a class that cannot be instantiated directly and serves as a base class for other classes. Abstract methods are methods declared within an abstract class that do not have an implementation (no method body). They are essentially contracts that derived classes must fulfill by providing their own implementation.
Abstract Class
- Declared using the
abstract
keyword before theclass
keyword. - Cannot be instantiated (you cannot create objects of an abstract class).
- Acts as a blueprint or template for other classes, providing a common structure and behavior.
- Can contain both abstract and concrete (non-abstract) methods.
- Abstract methods force derived classes to implement specific functionality.
- Abstract classes can inherit from other classes (including non-abstract classes) or implement interfaces.
Abstract Method
- Declared using the
abstract
keyword within an abstract class. - Must be part of an abstract class or an interface.
- Lacks a method body (no implementation).
- Derived classes are required to provide an implementation for the abstract method using the
override
keyword. - Abstract methods are implicitly virtual, so the
virtual
keyword is not needed when declaring them. override
keyword is necessary in the derived class to provide the implementation.
Example:
In this example,
Animal
is an abstract class with an abstract method GetSound()
and a concrete method Move()
. Dog
and Cat
are derived classes that inherit from Animal
. Both Dog
and Cat
must implement the GetSound()
method, while Dog
also overrides the Move()
method to provide its specific implementation. The Main
method demonstrates how to create instances of the derived classes and call their methods. Trying to create an instance of the abstract class Animal
directly would result in a compile-time error.
No comments:
Post a Comment