interface vs abstract class c# code example
Example 1: c# abstract class
abstract class Shape
{
public abstract int GetArea();
}
class Square : Shape
{
int side;
public Square(int n) => side = n;
public override int GetArea() => side * side;
static void Main()
{
var sq = new Square(12);
Console.WriteLine($"Area of the square = {sq.GetArea()}");
}
}
Example 2: abstract class vs interface
Interfaces specify what a class must do and not how.
It is the blueprint of the class.
It is used to achieve total abstraction.
We are using implements keyword for interface.
Abstract=
Sometimes we may come across a situation
where we cannot provide implementation to
all the methods in a class. We want to leave the
implementation to a class that extends it.
In that case we declare a class
as abstract by using abstract keyword on method
signature.In my framework I have created my
PageBase class as super
class of the all page classes.
I have collected all common elements
and functions into PageBase class and
all other page classes extent PageBase class.
By doing so, I don't have to locate very
common WebElements and it provides
reusability in my framework.
Also
1)Abstract classes cannot be instantiated
2)An abstarct classes contains abstract method,
concrete methods or both.
3)Any class which extends abstarct class must
override all methods of abstract class
4)An abstarct class can contain either
0 or more abstract method.
Example 3: c# abstract class and interfaces
public abstract class AbsParent {
private int count = 0;
public void foo1()
{
Console.WriteLine("Hi there, I'm a normal method that will be inherited!");
}
public abstract void foo2();
public virtual void foo3()
{
Console.WriteLine("Hi there, I'm a virtual method!");
}
}
public interface IParent {
string myProterty{get; set;}
void foo1();
void foo2();
}
public class Child1 : AbsParent {
public override void foo2()
{
Console.WriteLine("Only in the child/derived class, can I be defined!");
}
public override void foo3()
{
Console.WriteLine("Class name is Child1");
}
}
public class Child2 : IParent {
public void foo1()
{
Console.WriteLine("Only in the child/derived class, can I be defined!");
}
public void foo2()
{
Console.WriteLine("Only in the child/derived class, can I be defined!");
}
}
public class main_method {
public static void Main()
{
AbsParent obj = new AbsParent();
}
}