Java – object initialization using interfacetype
I've just come into contact with the Java programming language I have been programming in c# for two years When I browse the Java program, I find that the code is as follows
ArgumentParser parser = ArgumentParsers.newArgumentParser("text");
Argumentparser is an interfacetype and argumentparsers is a class But I can't find any implementation of argumentparser in argumentparsers We can create an interfacetype object by initializing the object with a class that does not implement the interface I didn't know c# it was possible Please explain it for me
thank you
Solution
You just call static methods in the ArgumentParsers class. You should check argumentparsers Newargumentparser implementation to see which argumentparser implementation is used
This is not unique to Java For example, like file Openread and xmlreader Methods such as create use return type declarations, which are abstract classes - the same is true for interfaces
For example, if you want to convert java code to C #, this will work:
public interface IArgumentParser { Configuration Parse(string[] arguments); } public static class ArgumentParsers { public static IArgumentParser(string file) { return new FileArgumentParser(file); } } internal class FileArgumentParser : IArgumentParser { private readonly string file; internal FileArgumentParser(string file) { this.file = file; } public Configuration Parse(string[] arguments) { // Presumably use the file somewhere... } }