Using Abstract Methods in a Derived Class
Nimesh Ekanayake
Technical Consultant @ Platned | MSc | Lecturer | IFS Certified x2 | Boomi Certified
An abstract method is a method that is declared in a base class but does not have an implementation. It is used to define a method signature that must be implemented by derived classes.
To use an abstract method in a derived class, you must first create a derived class that inherits from the base class. Then, you must override the abstract method in the derived class and provide an implementation for it.
Here is an example of an abstract method in a base class and how it is implemented in a derived class:
public abstract class Shap
{
? ? public abstract double Area();
}
public class Circle : Shape
{
? ? private double radius;
? ? public Circle(double radius)
? ? {
? ? ? ? this.radius = radius;
? ? }
? ? public override double Area()
? ? {
? ? ? ? return Math.PI * radius * radius;
? ? }
}
In this example, the Shape class defines an abstract method called Area. The Circle class is a derived class that inherits from Shape and provides an implementation for the Area method. The Circle class overrides the Area method by using the override keyword and providing a concrete implementation for it.
Once the abstract method has been implemented in the derived class, it can be used like any other method in the class. For example, you could call the Area method on an instance of the Circle class like this:
领英推荐
Circle circle = new Circle(5);
double area = circle.Area();
In this example, the Area method of the Circle class would be called, and the result of the method would be stored in the area variable.
Follow Nimesh Ekanayake ?on LinkedIn