An interface defines a group of public instance methods that a class must implement. It provides a way to enforce consistency across unrelated classes without requiring inheritance from a common base class.
By default, all interfaces are public, even if the public
keyword isn’t explicitly specified in the interface declaration. Likewise, all methods declared within an interface are public, and using the public
keyword is optional.
Steps to Create an Interface
In Server Explorer, right-click your project and select Add.
In the New Item dialog, choose Interface, assign it a name, and click Add.
When a class uses the implements
keyword, it must define all the methods declared in the interface. A class can implement multiple interfaces by listing them after the implements
keyword, separated by commas.
All implemented interface methods must be explicitly marked as public. The class itself must also be declared as public. An interface can inherit from one other interface using the extends
keyword, but it cannot extend more than one interface.
It is a common convention to begin interface names with an “I” (e.g., IDrivable
).
Interface Example
In the example below, the Automobile
class implements the IDrivable
interface. The is
keyword is used to check whether a class implements a particular interface.
interface IDrivable
{
int getSpeed()
{
}
void setSpeed(int newSpeed)
{
}
}
class Automobile implements IDrivable
{
int speed;
public int getSpeed()
{
return speed;
}
public void setSpeed(int newSpeed)
{
speed = newSpeed;
}
}
class UseAnAutomobile
{
void DriveAutomobile()
{
IDrivable drivable;
Automobile myAutomobile = new Automobile();
str temp;
myAutomobile = new Automobile();
if (myAutomobile is IDrivable)
{
drivable = myAutomobile;
drivable.setSpeed(42);
temp = int2str(drivable.getSpeed());
}
else
{
temp = "Instance is not an IDrivable.";
}
info(temp);
}
}