In C#, an abstract class is a class that cannot be instantiated. Instead, it serves as a base class for other classes to inherit from. Abstract classes are used to define a common set of behaviors or properties that derived classes should have.
To create an abstract class in C#, you use the “abstract” keyword before the class definition. Here is an example:
C#
using System;
public abstract class Animal
{
public abstract string Sound { get; }
public virtual void Move()
{
Console.WriteLine("Moving...");
}
}
public class Cat : Animal
{
public override string Sound => "Meow";
public override void Move()
{
Console.WriteLine("Walking like a cat...");
}
}
public class Dog : Animal
{
public override string Sound => "Woof";
public override void Move()
{
Console.WriteLine("Running like a dog...");
}
}
class Program
{
static void Main(string[] args)
{
Animal[] animals = new Animal[] { new Cat(), new Dog() };
foreach (Animal animal in animals)
{
Console.WriteLine($"The {animal.GetType().Name} goes {animal.Sound}");
animal.Move();
}
}
}
|
Output
The Cat goes Meow
Walking like a cat...
The Dog goes Woof
Running like a dog...
Abstraction in C# is the process to hide the internal details and show only the functionality. The abstract modifier indicates the incomplete implementation. The keyword abstract is used before the class or method to declare the class or method as abstract. Also, the abstract modifier can be used with indexers, events, and properties.
Example:
public abstract void geek();
// this indicates the method 'geek()' is abstract
abstract class gfg
// this indicates the class 'gfg' is abstract
Abstract Method: A method that is declared abstract, has no “body” and is declared inside the abstract class only. An abstract method must be implemented in all non-abstract classes using the override keyword. After overriding, the abstract method is in the non-Abstract class. We can derive this class in another class, and again we can override the same abstract method with it.
Syntax:
public abstract void geek();
// the method 'geek()' is abstract
Abstract Class: This is the way to achieve the abstraction in C#. An Abstract class is never intended to be instantiated directly. An abstract class can also be created without any abstract methods, We can mark a class abstract even if doesn’t have any abstract method. The Abstract classes are typically used to define a base class in the class hierarchy. Or in other words, an abstract class is an incomplete class or a special class we can’t be instantiated. The purpose of an abstract class is to provide a blueprint for derived classes and set some rules that the derived classes must implement when they inherit an abstract class. We can use an abstract class as a base class and all derived classes must implement abstract definitions.
Syntax:
abstract class gfg{}
// class 'gfg' is abstract
Important Points:
- Generally, we use abstract class at the time of inheritance.
- A user must use the override keyword before the method is declared as abstract in the child class, the abstract class is used to inherit in the child class.
- An abstract class cannot be inherited by structures.
- It can contain constructors or destructors.
- It can implement functions with non-Abstract methods.
- It cannot support multiple inheritances.
- It can’t be static.
Example 1: Program to show the working of an abstract class
C#
using System;
public abstract class GeeksForGeeks {
public abstract void gfg();
}
public class Geek1 : GeeksForGeeks
{
public override void gfg()
{
Console.WriteLine("class Geek1");
}
}
public class Geek2 : GeeksForGeeks
{
public override void gfg()
{
Console.WriteLine("class Geek2");
}
}
public class main_method {
public static void Main()
{
GeeksForGeeks g;
g = new Geek1();
g.gfg();
g = new Geek2();
g.gfg();
}
}
|
Output
class Geek1
class Geek2
Example 2: Program to calculate the area of a square using abstract class and abstract method
C#
using System;
abstract class AreaClass
{
abstract public int Area();
}
class Square : AreaClass
{
int side = 0;
public Square(int n)
{
side = n;
}
public override int Area()
{
return side * side;
}
}
class gfg {
public static void Main()
{
Square s = new Square(6);
Console.WriteLine("Area = " + s.Area());
}
}
|
Following are some important observations about abstract classes in C#
1) An Abstract class does not mean that it only contains abstract methods. An Abstract class can also contain non-abstract methods also.
Syntax:
abstract class gfg
{
public void geek()
{
Console.WriteLine("'geek()' is non-abstract method");
}
}
Example:
C#
using System;
abstract class AbstractClass {
public int AddTwoNumbers(int Num1, int Num2)
{
return Num1 + Num2;
}
public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}
class Derived : AbstractClass {
public override int MultiplyTwoNumbers(int Num1, int Num2)
{
return Num1 * Num2;
}
}
class geek {
public static void Main()
{
Derived d = new Derived();
Console.WriteLine("Addition : {0}\nMultiplication :{1}",
d.AddTwoNumbers(4, 6),
d.MultiplyTwoNumbers(6, 4));
}
}
|
Output
Addition : 10
Multiplication :24
2) Abstract class can also work with get and set accessors.
Example:
C#
using System;
abstract class absClass {
protected int myNumber;
public abstract int numbers
{
get;
set;
}
}
class absDerived : absClass {
public override int numbers
{
get
{
return myNumber;
}
set
{
myNumber = value;
}
}
}
class geek {
public static void Main()
{
absDerived d = new absDerived();
d.numbers = 5;
Console.WriteLine(d.numbers);
}
}
|
There are several advantages and disadvantages to using abstract classes in C#. Here are some of the main ones:
Advantages:
- Encapsulation: Abstract classes allow you to define a common set of behaviors or properties that derived classes should have, without
- exposing the implementation details of those behaviors or properties to the outside world. This can help you create more maintainable and flexible code.
- Code reuse: Abstract classes can be used as a base class for multiple derived classes, which can help reduce code duplication and improve code reuse.
- Polymorphism: Abstract classes can be used to achieve polymorphism, which allows you to write code that works with objects of different derived classes, as long as they all inherit from the same abstract base class.
Disadvantages:
- Tight coupling: Abstract classes can create tight coupling between the base class and derived classes, which can make it harder to modify the base class without affecting the derived classes.
- Limited inheritance: C# only allows a class to inherit from a single base class, so if you use an abstract class as a base class, you limit the ability of derived classes to inherit from other classes.
- Difficulty in testing: Because abstract classes cannot be instantiated directly, they can be more difficult to test than regular classes. In order to test a derived class, you may need to create a mock or stub of the abstract base class.
- Overall, abstract classes can be a powerful tool for creating flexible and maintainable code, but they should be used judiciously, taking into account the specific requirements of your application.
Similar Reads
C# | Abstract Classes
In C#, an abstract class is a class that cannot be instantiated. Instead, it serves as a base class for other classes to inherit from. Abstract classes are used to define a common set of behaviors or properties that derived classes should have. To create an abstract class in C#, you use the "abstrac
7 min read
Typescript Abstract Class
TypeScript, a superset of JavaScript, introduces many features to improve code organization, readability, and maintainability. One of these features is abstract classes. This article will explain what abstract classes are, how they work, and how to use them effectively in your TypeScript projects. T
3 min read
Abstract Classes in Python
In Python, an abstract class is a class that cannot be instantiated on its own and is designed to be a blueprint for other classes. Abstract classes allow us to define methods that must be implemented by subclasses, ensuring a consistent interface while still allowing the subclasses to provide speci
6 min read
C# | Abstraction
Data Abstraction is the property by virtue of which only the essential details are exhibited to the user. The trivial or the non-essentials units aren't exhibited to the user. Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring t
4 min read
Abstract Algebra
Abstract Algebra is a fascinating and essential branch of mathematics that deals with algebraic structures rather than traditional number systems. Unlike elementary algebra, which focuses on solving equations and manipulating formulas, abstract algebra explores more generalized concepts. These struc
12 min read
Scala | Abstract Type members
A member of a class or trait is said to be abstract if that particular member does not have a complete definition in the class. These Abstract members are always implemented in any sub-classes of the class under which it is defined. These kinds of declaration are allowed in many programming language
4 min read
Classes in SAP ABAP
SAP ABAP (Advanced Business Application Programming) is a high-level programming language created by the German software company SAP SE. ABAP is primarily used for developing and customizing applications within the SAP ecosystem, which includes enterprise resource planning (ERP) systems and other bu
7 min read
Constructor in Java Abstract Class
Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor. So if we do not define any constructor inside the abstract class then JVM (Java Virtual Machine) will g
4 min read
C# | Class and Object
Class and Object are the basic concepts of Object-Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single
5 min read
Messages, aggregation and abstract classes in OOPS
Object-Oriented Programming System (OOPS) is the basic concept of many programming languages. It is a paradigm based on the object which contains methods and data. This concept is used to make programming a class and object model which behaves like a real-world scenario. In this article, we'll learn
5 min read
C# | Object Class
The Object class is the base class for all the classes in the .Net Framework. It is present in the System namespace. In C#, the .NET Base Class Library(BCL) has a language-specific alias which is Object class with the fully qualified name as System.Object. Every class in C# is directly or indirectly
4 min read
Abstract Factory Pattern | C++ Design Patterns
Abstract Factory Pattern is a creational design pattern used in object-oriented programming. It provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern is a way to encapsulate the creation of objects and ensure that they are
6 min read
Difference between Abstract Class and Interface in C#
An abstract class is a way to achieve abstraction in C#. To declare an abstract class, we use the abstract keyword. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class
4 min read
Implement Interface using Abstract Class in Java
Interface contains only abstract methods that can't be instantiated and it is declared by keyword interface. A class that is declared with the abstract keyword is known as an abstract class in Java. This is a class that usually contains at least one abstract method which can't be instantiated and It
3 min read
Control Abstraction in Java with Examples
Our aim is to understand and implement Control Abstraction in Java. Before jumping right into control abstraction, let us understand what is abstraction. Abstraction: To put it in simple terms, abstraction is nothing but displaying only the essential features of a system to a user without getting in
3 min read
Abstract Factory Design Pattern in Java
The Abstract Factory Pattern in Java is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes, in simpler terms the Abstract Factory Pattern is a way of organizing how you create groups of things that ar
10 min read
Data Abstraction in Python
Data abstraction is one of the most essential concepts of Python OOPs which is used to hide irrelevant details from the user and show the details that are relevant to the users. For example, the readers of geeksforgeeks only know that a writer can write an article on geeksforgeeks, and when it gets
5 min read
Swift - Classes
Classes and Objects are building blocks of the Object-Oriented-Programming Paradigm. Class is a logical entity or a user-defined data type that has its own data members and member functions which can be accessed inside the class or outside it depending upon the access control allowed on each member.
8 min read
Abstract Method in Java with Examples
In Java, Sometimes we require just method declaration in super-classes. This can be achieved by specifying the Java abstract type modifier. Abstraction can be achieved using abstract class and abstract methods. In this article, we will learn about Java Abstract Method. Java Abstract MethodThe abstra
6 min read