Mar 16, 2007

Abstract Class Vs Interface

Abstract Class Vs Interface

There are a lot of discussion on the internet about the Interface vs Abstract class. and also , as BASE class whether we should use interface, abstract class or normal class.
Abstract Class vs Interface

We can not make instance of Abstract Class as well as Interface.
Here are few differences in Abstract class and Interface as per the definition.
Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).
Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are
by default public and abstract.

using System;
namespace ConsoleApplication2
{
/// /// Summary description for Class2. ///
public abstract class A
{
int someInt;
string someString;
public A()
{ // // TODO: Add constructor logic here // }
public abstract void F();
}

public class B : A
{
public override void F()
{ Console.WriteLine("F in B"); }
}

interface IA
{

//int someInt; give error we cant have fields in interface
//string someString;
string P{get;set;}
void F();
}
public class C : IA
{
public C() { }
public string P
{
get {return _p;}
set {_p = value;}
}
public void F()
{
Console.WriteLine("Abstract F()");
}
private string _p; }
}

we can make the call like this..
B b = new B();
b.F();
A a = b;
a.F();
//A a = new A(); will give error as we cant instantiate
C c = new C();
c.F();
c.P="Test String";
Console.WriteLine(c.P.ToString());
IA d = c;
d.F();
Console.WriteLine(c.P.ToString());
Console.Read();

Output :
F in B
F in B
Abstract F()
Test String
Abstract F()
Test String

We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties
allowed.
We use abstract class and Interface for the base class in our application.Now most important question: What should use : Interface force everybody to implement all things in that. So use it when u wanna force all the methods, properties, etc to implement.Abstract Class - limited you to create an instance of this class, and if you derived from this class you have to implement all abstract members to create an instance of this derived class. Also Abstract class should used when you have some functions which you must override and some which you can leave in this scenerio use abstract classes,

No comments:

Post a Comment

SQL - Difference between CAST,CONVERT and PARSE

TODO---