0% found this document useful (0 votes)
24 views

Interface

C# supports multiple inheritance through interfaces instead of directly inheriting from multiple base classes. An interface defines a contract that a class promises to fulfill by implementing the interface. Interfaces can inherit other interfaces and a class can implement multiple interfaces, allowing it to take on behaviors from different class hierarchies. When a class implements multiple interfaces, it must explicitly specify which interface a method is implementing to avoid name collisions. Interfaces can also be used to define arrays of common behaviors to group unrelated types.

Uploaded by

mohammedansil791
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Interface

C# supports multiple inheritance through interfaces instead of directly inheriting from multiple base classes. An interface defines a contract that a class promises to fulfill by implementing the interface. Interfaces can inherit other interfaces and a class can implement multiple interfaces, allowing it to take on behaviors from different class hierarchies. When a class implements multiple interfaces, it must explicitly specify which interface a method is implementing to avoid name collisions. Interfaces can also be used to define arrays of common behaviors to group unrelated types.

Uploaded by

mohammedansil791
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Interface

In C#, classes in C# cannot have more than one superclass.

For instance, a definition like

class A : B, C
{
....
....
}
is not permitted in C#.

However, the designers of C# could not overlook the importance of multiple inheritance.

A large number of real-life applications require the use of multiple inheritance whereby we
inherit methods and properties from several distinct classes.

Since ‘C++ - like’ implementation of multiple inheritance proves difficult and adds
complexity to the language, C# provides an alternate approach known as interface to support
the concept of multiple inheritance.

Although a C# class cannot be a subclass of more than one superclass, it can implement more
than one interface, thereby enabling us to create classes that build upon other classes without
the problems created by multiple inheritance.

An interface in C# is a reference type.

It is basically a kind of class with some differences.

Major differences include:

1. All the members of an interface are implicitly public and abstract.


2. An interface cannot contain constant fields, constructors and destructors.
3. Its members cannot be declared static.
4. Since the methods in an interface are abstract, they do not include implementation code.
5. An interface can inherit multiple interfaces.

Defining an interface

An interface can contain one or more methods, properties, indexers and events but none of
them are implemented in the interface itself.

It is the responsibility of the class that implements the interface to define the code for
implementation of these members.

The syntax for defining an interface is very similar to that used for defining a class.
The general form of an interface definition is

interface InterfaceName
{
Member declarations;
}

Here, interface is the keyword and InterfaceName is a valid C# identifier (just like class
names).

Member declarations will contain only a list of members without implementation code.

Given below is a simple interface that defines a single method.

interface Show
{
void Display ( ); // Note semicolon here
}

Extending an interface

Like classes, interfaces can also be extended.

That is, an interface can be subinterfaced from other interfaces.

The new subinterface will inherit all the members of the superinterface in the manner similar
to subclasses.

This is achieved as follows:

interface name2 : name1


{
Members of name2
}

For example, we can put all members of particular behavior category in one interface and the
members of another category in the other.

Consider the code below.

interace Addition
{
int Add (int x, int y) ;
}

interface Compute : Addition


{
int Sub (int x, int y);
}
The interface Compute will have both the methods and any class implementing the interface
Compute should implement both of them; otherwise, it is an error.

We can also combine several interfaces together into a single interface. Following
declarations are valid:

interface I1
{....
}
interface I2
{....
}
interface I3 : I1, I2 //multiple inheritance
{....
}

While interfaces are allowed to extend other interfaces, subinterfaces cannot define the
methods declared in the superinterfaces.

After all, subinterfaces are still interfaces, not classes. It is the responsibility of the class that
implements the derived interface to define all the methods.

Note that when an interface extends two or more interfaces, they are separated by commas.

It is important to remember that an interface cannot extend classes. This would violate the
rule that an interface can have only abstract members.

Implementing interfaces

Interfaces are used as ‘superclasses’ whose properties are inherited by classes.

It is therefore necessary to create a class that inherits the given interface.

This is done as follows:

class classname : interfacename


{
body of classname
}

Here the class classname ‘implements’ the interface interfacename.

A more general form of implementation may look like this:

class classname : superclass, interface1, interface2. . . .


{
body of classname
}
This shows that a class can extend another class while implementing interfaces.

In C#, we can derive from a single class and, in addition, implement as many interfaces as the
class needs.

When a class inherits from a superclass, the name of each interface to be implemented must
appear after the superclass name.

Example:

class A : B, I1, I2, . . . . .


{
.....
}

where B is a base class and I1, I2, . . . . are interfaces.

The base class and interfaces are separated by commas.

Example:

using System;
interface Addition
{ int Add ( );
}
interface Multiplication
{
int Mul ( );
}
class Computation : Addition, Multiplication
{
int x, y;
public Computation (int x, int y ) //Constructor
{ this.x = x; this.y = y;
}
public int Add ( ) //Implement Add ( )
{
return ( x + y );
}
public int Mul ( ) //Implement Mul ( )
{
return ( x * y );
}
}
class InterfaceTest1
{
public static void Main( )
{
Computation com = new Computation (10,20);
Addition add = (Addition) com; // casting
Console.WriteLine (“Sum = ” + add.Add ( ));
Multiplication mul = (Multiplication) com; // casting
Console.WriteLine(“Product = ” + mul.Mul ( ) );
}
}

Multiple implementation of an interface

It is the case where an interface is implemented by multiple classes.

Example:

using System;
interface Area
{
double Compute ( double x );
}
class Square : Area
{
public double Compute (double x)
{
return (x * x)
}
}
class Circle : Area
{
public double Compute (double x)
{
return (Math.PI * x * x);
}
}
class InterfaceTest2
{
public static void Main( )
{
Square sqr = new Square ( );
Circle cir = new Circle ( );
Area area;
area = sqr as Area; //casting
Console.WriteLine (“Area of Square =” + area.Compute(10.0));
area = cir as Area; //casting
Console.WriteLine (“Area of Circle=” + area.Compute(10.0));
}
}
Interfaces and inheritance

Most often we have situations where the base class of a derived class implements an
interface.

In such situations, when an object of the derived class is converted to the interface type, the
inheritance hierarchy is searched until it finds a class that directly implements the interface.

Example:

using System;
interface Display
{
void Print ( );
}
class B : Display // implements Display
{
public void Print ( )
{
Console.WriteLine(“Base Display”);
}
}
class D : B // inherits B class
{
public new void Print ( )
{

Console.WriteLine(“Derived Display”);
}
}
class InterfaceTest3
{
public static void Main( )
{
D d = new D ( );
d.Print ( );
Display dis = (Display) d; dis.Print ( );
}
}

Explicit interface implementation

One of the reasons that C# does not support multiple inheritance is the problem of name
collision.

However, this problem still persists in C# when it implements more than one interface.
Example:

interface I1
{
void Display ( );
}

interface I2

{
void Display ( );
}

class C1 : I1, I2
{
public void Display { }
}

Does C1.Display( ) implement I1.Display( ), or I2.Display( )?

It is ambiguous and so the compiler reports an error. Such problems of name collision may
occur when we implement interfaces from different sources.

C# supports a technique known as explicit interface implementation, which allows a method


to specify explicitly the name of the interface it is implementing.

Example:

using System;
interface I1
{
void display ( );
}
interface I2
{
void Display ( );
}
class C1 : I1, I2
{
void I1.Display()
{
Console.WriteLine(“I1 Display”);
}
void I2.Display()
{
Console.WriteLine(“I2 Display”);
}
}
class InterfaceTest4
{
public static void Main( )
{
C1 c = new C1( );
I1 i1 = (I1) c;
i1.Display();
I2 i2 = (I2)c;
i2.Display ( );
}
}

Array of Interfaces

Interface can use the concept of arrays to store multiple values.

Example:

interface IShape
{
double CalArea();
}

class Circle : IShape


{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public double CalArea()
{
return Math.PI * radius * radius;
}
}

class Rectangle : IShape


{
private double width, height;
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public double CalArea()
{
return width * height;
}
}
class Program
{
static void Main(string[] args)
{
IShape[] shapes = new IShape[3];

Console.WriteLine("Enter the radius of circle 1: ");


int r1 = int.Parse(Console.ReadLine());
shapes[0] = new Circle(r1);

Console.WriteLine("Enter the length and breadth of rectangle 1:");


int l1 = int.Parse(Console.ReadLine());
int b1 = int.Parse(Console.ReadLine());
shapes[1] = new Rectangle(l1, b1);

Console.WriteLine("Enter the radius of circle 2: ");


int r2 = int.Parse(Console.ReadLine());
shapes[2] = new Circle(r2);

Console.WriteLine("Areas of shapes:");
foreach (IShape shape in shapes)
Console.WriteLine(shape.CalArea());
Console.ReadKey();
}
}

You might also like