xxxxxxxxxx
/*
-Abstract modifier states that a class or a member misses implementation. We
use abstract members when it doesn’t make sense to implement them in a base
class. For xample, the concept of drawing a shape is too abstract. We don’t
know how to draw a shape. This needs to be implemented in the derived classes.
-When a class member is declared as abstract, that class needs to be declared
as abstract as well. That means that class is not complete.
-In derived classes, we need to override the abstract members in the base
class.
-In a derived class, we need to override all abstract members of the base class,
otherwise that derived class is going to be abstract too.
-Abstract classes cannot be instantiated
*/
public abstract class Shape
{
// This method doesn’t have a body.
public abstract Draw();
}
public class Circle : Shape
{
public override Draw()
{
// Changed implementation
}
}
xxxxxxxxxx
Abstract class: is a restricted class that cannot be used to create objects
(to access it, it must be inherited from another class).
xxxxxxxxxx
An abstract class in an unfinished class
whose purpose is to define some common definitions for its subclasses.
It must be implemented in its subclasses.
Abstract class is created with the abstract keywords.
We can create abstract methods and member fields.
Abstract classes cannot be instantiated and
abstract methods cannot be implemented.
xxxxxxxxxx
// Example of an abstract class in C#
public abstract class Animal
{
public abstract void MakeSound(); // Abstract method
public void Eat()
{
Console.WriteLine("Animal is eating.");
}
}
// Example of a derived class inheriting from the abstract class
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog is barking.");
}
}
// Example usage of the abstract class and derived class
static void Main()
{
Animal myDog = new Dog();
myDog.MakeSound(); // Output: Dog is barking.
myDog.Eat(); // Output: Animal is eating.
}
xxxxxxxxxx
abstract class Shape
{
public abstract double GetArea();
}
class Triangle : Shape
{
double baseLength;
double height;
public Triangle(double baseLength, double height)
{
this.baseLength = baseLength;
this.height = height;
}
public override double GetArea()
{
return 0.5 * baseLength * height;
}
}
class Rectangle : Shape
{
double width;
double height;
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public override double GetArea()
{
return width * height;
}
}
class Program
{
static void Main(string[] args)
{
Shape triangle = new Triangle(4, 5);
Shape rectangle = new Rectangle(3, 6);
Console.WriteLine("Triangle area: " + triangle.GetArea());
Console.WriteLine("Rectangle area: " + rectangle.GetArea());
}
}