Tuesday, 20 August 2013

What is Abstract Classes in C#


What is Abstract Classes:  

Abstract classes are classes that contain only the declaration of the method; whereas, the method is defined in the class. In other word, abstract classes are similar to the base classes except that method declared inside the abstract classes, know as abstract methods, do not have method bodies

    The following are some important characteristics of abstract classes.

  •   An abstract class is declared by using the abstract keyword
  •     An abstract class is always public
  •  An abstract class can contain both abstract and non-abstract method
  •  An abstract class must have least one abstract method
  • Each class derived from an abstract class must provide implementation for all the abstract methods of the abstract class.
  •    You cannot create an object of an abstract class. To use the functionality specified in an abstract class, you need to first derive a new class from the abstract class. 
  •  Non abstract method of abstract class is invoked using object  variable of sub class


The syntax to declare an abstract class in C# is as follows:

[access modifier] abstract  class <className>
{
// content methods of  an abstract class
}

Example with Abstract Class:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AbstractClasses
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// create abstract class Shape
public abstract class Shape
{
// abstract method..............
public abstract void Area(double x);

//non-abstract method.............
public void Circumference(double r)
{
double res = 2 * 3.14 * r;
MessageBox.Show("The Circumference of Circle is = " + res);

}

}
public class Circle : Shape
{

public override void Area(double radius)
{
double result = 3.14 * radius * radius;
MessageBox.Show("The Area of Circle is = " + result);
}

}
public class Square : Shape
{
public override void Area(double side)
{
double result = side * side;
MessageBox.Show("The Area of Square is =" + result);
}
}

Call above class on btnGetArea Click………………………………………………..
private void btnGetArea_Click(object sender, EventArgs e)
{
Circle c = new Circle();
c.Area(Convert.ToDouble(txtradius.Text));

//Non abstract method of abstract class is invoked using object  variable of sub class
c.Circumference(Convert.ToDouble(txtradius.Text));

Square s = new Square();
s.Area(Convert.ToDouble(txtside.Text));

}
}
}


0 comments:

Post a Comment