Interface
Interface looks similar to a class, but it does not contain implementation. They may contain declarations of events, indexers, methods and properties.
With Interfaces, it is easier to achieve plug-n-play like architectures where components can be interchanged at will. Since same interface is implemented through all the components and hence all the components can be used without any additional programming. All the members of interface are public. It is also helpful in defining the standard structure that the implementing classes would follow.
Using the interface keyword an Interface is declared. It is similar to class declaration. In standard naming conventions, the interface name starts with I. There is no language-based constraint on this. Instead, this is a convention. An interface can inherit from one or more base interfaces.
interface ITesting
{
void DoTest();
}
class ImplementationClass : ITesting
{
public void DoTest()
{
// Method implementation.
}
}
Abstract
Abstract modifier can be used with classes, methods, properties, indexers, and events.
No object of an abstract class can be instantiated. Abstract class can be used as base class. Abstract members of abstract class must be used in sub classes. Abstract class does not implement the member. Members marked as abstract, must be implemented by classes that derive from the abstract class. Abstract class may implement code with non-Abstract methods.
abstract class TestBase
{
public abstract void StartTest();
}
Abstract methods do not contain body. They must be implemented in the class that inherits their class, using override keyword. The access modifier of the abstract method must be same in both the abstract class and its derived class. We cannot use private access modifier for abstract methods.
abstract class TestBase
{
public string Run()
{
return "Test started";
}
public abstract void InitializeTest();
}
public class EmployeeTest : TestBase
{
public override void InitializeTest ()
{
}
}
Difference b/w Interface and Abstract class
- Defining an abstract class with abstract members has the same effect to defining an interface. But an abstract class can have abstract members as well as non abstract members. These non abstract members can be referenced through the derived classes. An interface, on the other hand, cannot have fields.
- Interface support multiple inheritance while abstract class does not.
- Interface doesn’t contain constructors, while abstract class can have constructors.
- The members of the interface are public by default with no implementation. Abstract classes can have protected parts, static methods, etc.
0 Comment(s)