Abstract Class With Abstract Method C# With Example



An abstract class can contain both abstract methods and non-abstract (concrete) methods.
It can contain both static and instance variables.
The abstract class cannot be instantiated but its reference can be created.
If any class contains abstract methods then it must be declared by using the keyword abstract.
An abstract class can contain sealed methods but an abstract method or class cannot be declared as sealed.
A subclass of an abstract class can only be instantiated if it implements all

using System;

namespace CSharpInheritance
{
	abstract class Shape
	{
		public double dim1, dim2;

		public Shape(double dimension1, double dimension2)
		{
			dim1 = dimension1;
			dim2 = dimension2;
		}

		abstract public double area();
	}
	class Rectangle : Shape
	{
		public Rectangle(double dimension1, double dimension2):base(dimension1, dimension2){}

		override public double area()
		{
			Console.WriteLine("\nInside Area for Rectangle : ");
			return dim1 * dim2;
		}
	}

	class Triangle : Shape
	{
		public Triangle(double dimension1, double dimension2):base(dimension1, dimension2){}

		override public double area()
		{
			Console.WriteLine("\nInside Area for Triangle : ");
			return dim1 * dim2 / 2;
		}
	}

	class AbstractClass
	{
		public static void Main(string[] args)
		{
			Rectangle newRectangle = new Rectangle(6,7);
			Triangle newTriangle = new Triangle(12,23);

			Shape referenceShape;

			referenceShape = newRectangle;
			Console.WriteLine("Area is " + referenceShape.area());

			referenceShape = newTriangle;
			Console.WriteLine("Area is " + referenceShape.area());
		}
	}
}

0 Comment's

Comment Form