Interface
|
Abstract Class
|
Interface Keyword is given before the
name of the Interface
public interface IAbc
{
////
}
|
Abstract keyword is used before the name of the class
public abstract class Abc
{
////
|
Only method declarations must be in the interface (No fields, no properties in
the interface)
public interface IAbc
{
public void Method1();
public void Method2();
public string Method3();
protected int Method4();
}
|
Atleast one or more abstract
methods must be in the abstract class (or)
All the methods may be abstract and fields, properties, delegates can
be declared in abstract class
public abstract class Abc
{
public abstract void Method1();
public void Method2()
{
Console.WriteLine("I am Method2");
}
protected abstract string Method3();
public int Method4()
{
int a=10;
int b=20;
return (a + b);
}
}
|
By default methods declarations in interface are public. We can
declare public or protected in interface.
|
By default methods in a class or abstract class are private.
We can declare public or protected abstract classes.
|
All the method declarations in interface must be implemented in
derived class.
class Xyz : IAbc
{
public void Method1()
{
Console.WriteLine("I am Method1");
}
public void Method2()
{
Console.WriteLine("I am Method2");
}
public string Method3()
{
string a = "Koding
Attitude";
return a;
}
protected int Method4()
{
int a=10;
int b=20;
return (a + b);
}
}
|
The abstract methods may or may not be implemented in derived class
i.e., only necessary abstract methods can be implemented.
class Xyz : Abc
{
public override void Method1()
{
Console.WriteLine("Overrided Abstract
Method1");
}
protected override void Method3()
{
Console.WriteLine("Overrided Abstract
Method3");
}
}
|
An interface cannot be inherited from a class.
Actually interface name starts with ‘I’, but it is not mandatory.
|
An abstract class can be inherited from a class, but we cannot create
instance for abstract class.
|
We cannot create instance for interface, but we can create reference
to the interface by using child class reference object.
class Pqr
{
IAbc obj = new Xyz();
obj.Method1();
}
|
Even though abstract class can have constructor, it is not possible
to create instance for abstract class, As abstract class is having partial
implementation
|
Tuesday, 25 July 2017
Difference between Interface and Abstract Class In C# ?
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: only a member of this blog may post a comment.