Abstract Class:
Above shown is the error when trying to create an object (obj) of an abstract class Class1
public abstract class Class1
{
}
public class class2 : Class1
{
}
here Cass2 inherits Class1
public abstract class Class1
{
public abstract void add();
// add is an abstract method which is with out body its only the definition of the method
}
-
an abstract method can not be private it has to be public, protected or internal
-
there can be any number of abstract method in a abstract class
-
an abstract method can not be written for non abstract class
-
an abstract class can have other methods also which are not abstract methods
public abstract class Class1
{
public abstract void add();
private void sub()
{
}
}
5.When an abstract class is inherited by another class ,the derived class which is inheriting the abstract class must have the implementation of the abstract method with override key word other wise it will give a compile time error as shown below
the correct code for this is
public abstract class Class1
{
public abstract void add();
private void sub()
{
}
}
public class class2 : Class1
{
public override void add()
{
}
}
whats the use of an abstract class?
The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
Example
using System;
using System.Collections.Generic;
using System.Text;
namespace AbstractClassEx
{
public abstract class Class1
{
public abstract void add();
private void sub()
{
}
}
public class class2 : Class1
{
public override void add()
{
throw new Exception("The method or operation is not implemented.");
}
}
}