Introduction
This post will show how to use interface.
Table of contents
- What is interface?
- How to use interface in C# program
- Example
- Introduction to our game
- Conclusion
What is interface?
In object-oriented programming languages, there exists a feature called interface. As C# is object-oriented programming languages, we can use interface. By using interface, the design of a program becomes more flexible and accessible.
Advantages
- Allows for loose coupling of classes.
- Ensures functionality of classes.
- Enables secure access to classes.
How to use interface in C# program
Here's how you would describe it:
interface interfaceName
{
// method
void methodName1(string variable1, string variable2)
void methodName2(int variable1, int variable2)
}
Interfaces do not have implementations of methods or fields; they only have the type of methods. The actual implementation of methods is required in each class.
The methods defined in the interface mush be implemented within the class.
Example
Example the interface of phone.
interface IPhone
{
// method
void Call(string number);
}
Classes including this interface are guaranteed to have a method called "Call". Additionally, users can only invoke the "Call " method through the interface.
Example the class including the interface.
// CellPhone Class Including IPhone interface
class CellPhone : IPhone # define interface you want to use
{
// mail address
private string mailAddress;
// number
private string number;
// constructor
public CellPhone(string mailAddress, string number)
{
this.mailAddress = mailAddress;
this.number = number;
}
// call the designated number
public void Call(string number)
{
Debug.Log("Call the number: " + number);
}
}
Accessing through the interface provides clarity to users about which methods to use and makes the definition of arguments clear and easy to use. Additionally, it manages fields, preventing users from accidentally accessing unnecessary fields.
Introduction to our game
We are using interfaces in the game we're developing, particularly for defining items. By defining an interface for items and classes for each item, we can develop processing logic for each item individually. This approach allows us to use item program easily by using the interface from the user's perspective.
public interface Item
{
// fade item
public void SetActiveFalse();
// display item
public void SetActiveTrue();
// use item
public bool UseItem(Camera cam);
}
Conclusion
Using interfaces not only simplifies understanding for team members collaborating on development but also enhances development efficiency. It seems like adding new items in the future will be easily manageable. We look forward to further leveraging interfaces in our development process.
Top comments (0)