Console C#.Net Tutorial

Visual Studio.NET IDE

Define C#.NET

C# Comment

C# Variables

C# Data Types

C# Escape Sequence

C# Operators

Format String

Operator Precedence

C# Keywords

Constant Variable

Type Conversion

Flow Control

C# Arrays

C# Character

C# Strings

User-Define Methods

Variable Scope

C# Enumerations

C# Structure

C# Exception Handling

Object Oriented Programming

C# Classes

Constructor & Destructor

C# Inheritance

C# Polymorphism

C# Operator Overloading

C# Method Overriding

C# Interface

Abstract Classes & Methods

Sealed Classes, Methods

C# Properties

C# Indexer

C# Delegates

C# Generics

C# Collection

C# ArrayList

C# Stack

C# Queue

C# HashTable

C# SortedList

Page Stats

Visitor: 198

C#.Net Abstract Classes and Abstract Methods

Abstraction is the process to hide the internal details and showing only the functionality. The keyword abstract is used before the class or method name. An Abstract class cannot be instantiated directly, it need to be inherited. Abstract classes may have abstract members. The Abstract classes are typically used to define a base class.

Example 1: Abstract class declaration. The example below produce a error message as abstract class cannot be instantiated.

namespace AbstractClass
{
    abstract class Class1
    {
        public void method()
        {
            Console.WriteLine("This is a method");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class1 obj = new Class1(); //Error: cannot create an instance of the abstract class
            obj.method();
            Console.Read();
        }
    }
}

Example 2: Abstract class declaration with inheritance.

namespace AbstractClass2
{
    abstract class Class1
    {
        public void method()
        {
            Console.WriteLine("This is a abstract class method");
        }
    }
	class Class2
	{
		public void method2()
		{
			Console.WriteLine("This is a derived class method");
		}
	}
    class Program
    {
        static void Main(string[] args)
        {
            Class2 obj = new Class2();
            obj.method();
            obj.method2();
            Console.Read();
        }
    }
}

Abstract method is declared in base class without definition. So it is the responsibility of the derived class to implementation an abstract method.

abstract class Class1
{
	public abstract void method() //Error cannot declare a body.
	{
		Console.WriteLine("This is a method");
	}
}

Example 3: Program to calculate the area of a square using abstract class and abstract method

abstract class AreaClass 
{ 
    abstract public int Area(int); 
} 
  
class Square : AreaClass 
{ 
    public override int Area(int side) 
    { 
        return side * side; 
    } 
} 
  
class AbstractMethod { 
  
    public static void Main() 
    { 
        Square sq = new Square(); 
        Console.WriteLine("Area  = " + sq.Area(5));
        Console.Read();		
    } 
}