I have been using interface and abstract class and been overlooking few things. I always ignored few things which are important I would like to know about in depth now:
So I understand Abstraction is process of hiding unneeded functionality from user,I am wondering when using Interface, it provides abstraction and hides unnecessary code . I want to know who is user in below code and where is abstraction actually happening.
public class Program
{
public static void Main()
{
IFile file1 = new FileInfo();
FileInfo file2 = new FileInfo();
file1.ReadFile();
file1.WriteFile("content");
file2.ReadFile();
file2.WriteFile("content");
}
}
interface IFile
{
void ReadFile();
void WriteFile(string text);
}
class FileInfo : IFile
{
public void ReadFile()
{
Console.WriteLine("Reading File");
}
public void WriteFile(string text)
{
Console.WriteLine("Writing to file");
}
}
Please explain me who is user here and where is Abstraction Happening. I have weak brain when it comes to understand some definitions.
>Solution :
The Main method in the Program class is the user. The Main method creates instances of the IFile interface and the FileInfo class, and calls their methods.
Abstraction is used in the code through the IFile interface. The interface abstracts away the specific implementation details of the FileInfo class. The user (the Main method) interacts with the IFile interface, which provides a set of methods (namely, ReadFile and WriteFile) that define the desired functionality. The user does not need to know about the internal implementation of the FileInfo class; they only need to know about the abstraction provided by the interface.
By using the interface, abstraction is achieved by hiding unnecessary code details and exposing a simplified interface that focuses on the desired functionality. The user can use the ReadFile and WriteFile methods without worrying about how they are implemented in the FileInfo class.
In summary, the user is the Main method, and abstraction is happening through the use of the IFile interface, which hides the implementation details of the FileInfo class and provides a simplified and consistent interface for working with files.
Here is an analogy that might help you understand abstraction in this context:
Imagine you are a customer at a restaurant. You don’t need to know how the chef cooks your food in order to enjoy it. You simply order your food from the menu and the chef takes care of the rest. The chef is the implementation detail, and the menu is the abstraction. The menu provides you with a simplified interface that allows you to order the food you want without having to worry about the details of how it is cooked.
In the same way, the IFile interface provides a simplified interface that allows the user to work with files without having to worry about the details of how they are implemented. This is achieved through abstraction.