Abstract Class and An Interface
Abstract Class :
The class which cannot be instantiated is known as an Abstract Class. So an object of it cannot be created. Hence it must be inherited.- Can't be instantiated.
- Must be inherited.
- It may have Concrete Methods & Abstract Methods.
- An Abstract Class can have only Abstract Method.
- An Abstract Method must be overridden.
public abstract class AbstractA
{
public abstract string AbstractProperty { get; set; }
public abstract void AbstractFunction1();
public virtual void AbstractFunction2()
{
Console.WriteLine("AbstractA : AbstractFunction2()");
}
public void AbstractFunction3()
{
Console.WriteLine("AbstractA : AbstractFunction3()");
}
public void AbstractFunction4()
{
Console.WriteLine("AbstractA : AbstractFunction4()");
}
}
public class ClassA : AbstractA
{
private string classProperty;
public override string AbstractProperty
{
get
{
return classProperty;
}
set
{
classProperty = value;
}
}
public override void AbstractFunction1()
{
Console.WriteLine("ClassA : AbstractFunction1()");
}
public override void AbstractFunction2()
{
Console.WriteLine("ClassA : AbstractFunction2()");
}
public new void AbstractFunction3()
{
Console.WriteLine("ClassA : AbstractFunction3()");
}
}
---------------------------------------------------------------------
ClassA classA = new ClassA();
classA.AbstractFunction1();
classA.AbstractFunction2();
classA.AbstractFunction3();
classA.AbstractFunction4();
classA.AbstractProperty = "AbstractProperty_New Value";
classA.AbstractProperty = "AbstractProperty_New Value";
Console.WriteLine(classA.AbstractProperty);
ClassA : AbstractFunction1()
ClassA : AbstractFunction2()
ClassA : AbstractFunction3()
AbstractA : AbstractFunction4()
AbstractA : AbstractFunction4()
AbstractProperty_New Value
An Interface :
- Have definition of a method not implementation. (implement through class)
- Multiple inheritance possible through Interface only
- Only Public Access modifier only allowed. Default is Public
- No need of virtual overridden.
- It’s used for to define a set of properties, methods and events.
public interface InterfaceA
{
string InterfaceProperty { get; set; }
void InterfaceFunction1();
void InterfaceFunction2();
}
public class ClassB : InterfaceA
{
private string classProperty;
public string InterfaceProperty
{
get
{
return classProperty;
}
set
{
classProperty = value;
}
}
public void InterfaceFunction1()
{
Console.WriteLine("ClassB : InterfaceFunction1()");
}
public void InterfaceFunction2()
{
Console.WriteLine("ClassB : InterfaceFunction2()");
}
}
---------------------------------------------------------------------
ClassB classB = new ClassB();
classB.InterfaceFunction1();
classB.InterfaceFunction2();
classB.InterfaceProperty = "InterfaceProperty_New Value";
Console.WriteLine(classB.InterfaceProperty);
ClassB : InterfaceFunction1()
ClassB : InterfaceFunction2()
InterfaceProperty_New Value
Comments