The following program demonstrates an Example of Abstract Class in C#.
In this example, we have declared an abstract class Shape. An abstract class doesn’t have a complete definition. In other words, some of the methods of an abstract class are not defined. These methods are abstract methods. In fact, an abstract class can contain abstract as well as non-abstract methods. Also, the abstract methods are declared with the abstract keyword.
Furthermore, we can not create an instance of the abstract class. So, only the concrete subclasses of the abstract class can be used to create objects. Also, if an abstract class has abstract methods, then all of its concrete subclasses must provide the definition of all abstract methods. In order to define the abstract methods of the abstract superclass, the subclasses of an abstract class must use the override keyword.
using System;
namespace AbstractClassDemo
{
class Program
{
static void Main(string[] args)
{
Rectangle ob1 = new Rectangle(3, 5);
Console.WriteLine(ob1.area());
Triangle ob2 = new Triangle(5,3);
Console.WriteLine(ob2.area());
}
}
abstract class Shape
{
protected int dimension1, dimension2;
public abstract double area();
}
class Rectangle: Shape
{
public Rectangle()
{
dimension1 = 1; dimension2 = 1;
}
public Rectangle(int length, int breadth)
{
dimension1 = length;
dimension2 = breadth;
}
public override double area()
{
Console.WriteLine("Area of Rectangle: ");
return dimension1 * dimension2;
}
}
class Triangle : Shape
{
public Triangle()
{
dimension1 = 1; dimension2 = 1;
}
public Triangle(int length, int height)
{
dimension1 = length;
dimension2 = height;
}
public override double area()
{
Console.WriteLine("Area of Triangle: ");
return 0.5 *dimension1 * dimension2;
}
}
}
Output
Further Reading
How to Create Instance Variables and Class Variables in Python
Comparing Rows of Two Tables with ADO.NET
Example of Label and Textbox Control in ASP.NET
One Dimensional and Two Dimensuonal Indexers in C#
Private and Static Constructors in C#
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML