Junior
How is the request to the interface made?
sobes.tech AI
Answer from AI
A request to an interface is made by calling methods or accessing properties of an instance of a class that implements this interface. You cannot create an instance of the interface itself.
Example:
// Interface declaration
public interface ILogger
{
void LogMessage(string message);
}
// Class implementing the interface
public class ConsoleLogger : ILogger
{
public void LogMessage(string message)
{
Console.WriteLine(message);
}
}
// Using the interface
public class Application
{
private readonly ILogger _logger;
public Application(ILogger logger) // Dependency on the interface
{
_logger = logger;
}
public void Run()
{
_logger.LogMessage("Application started."); // Calling method via interface
}
}
// Entry point
public class Program
{
public static void Main(string[] args)
{
ILogger logger = new ConsoleLogger(); // Creating an instance of a class that implements the interface
Application app = new Application(logger);
app.Run();
}
}
Main principles:
- Polymorphism: Allows referring to different implementations of an interface through a single data type (the interface).
- Abstraction: Hides implementation details and works only with the contract defined by the interface.
- Using an instance: A request to an interface always occurs through an instance of a class that implements the methods and properties declared in the interface.