Introduction to class and interface
The class is declared using the class keyword, the class has its own name and the class members are surrounded by curly braces. Each class has a constructor. This constructor is automatically called whenever an instance of the class is created. The constructor does not have a return value, and the constructor’s name is always the same as the class name.
The interface looks like a class, but there is no implementation of the interface. The interface only contains declaration of events, methods and properties. The interface can only be inherited by classes, and it includes the implementation of each interface member.
Example of C # Classes: Classes.cs
// Namespace Declaration
using System;
class OutputClass
{
string myString;
// Constructor
public OutputClass(string inputString)
{
myString = inputString;
}
// Instance Method
public void printString()
{
Console.WriteLine("{0}", myString);
}
// Destructor
~OutputClass()
{
// Some resource cleanup routines
}
}
// Program start class
class ExampleClass
{
// Main begins program execution.
public static void Main()
{
// Instance of OutputClass
OutputClass outCl = new OutputClass("This is printed by the output class.");
// Call Output class' method
outCl.printString();
}
}
Output has a constructor, instance method and a destructor. It also has a field named myString.
Interface
interface MyInterface
{
void MethodToImplement();
}
This method has no implementation because the interfac specifies only the methods that should be implemented in the class.
Using interface
class UseInterface : MyInterface
{
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
static void Main()
{
UseInterface oi = new UseInterface();
oi.MethodToImplement();
}
}
An interface can implement another interface as well.
Abstract class vs interface
- An abstract class doesn’t provide full abstraction but an interface does provide full abstraction; i.e. both a declaration and a definition is given in an abstract class but not so in an interface.
- Using abstract we cannot achieve multiple inheritance but using an Interface we can achieve multiple inheritance.
- We can not declare a member field in an Interface.
- We can not use any access modifier i.e. public, private, protected, internal etc. because within an interface by default everything is public.
- An Interface member cannot be defined using the keyword static, virtual, abstract or sealed.