I like to know is there any specific reason that there is no public constructor in Pattern and Matcher class of java?
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Many frameworks avoid the use of direct constructors for complex objects, preferring instead more elegant factories.
A pattern is generated by ‘compiling’ a regular expression, so you make a static call to the ‘compile’ method. It initializes everything that is necessary. A matcher is specific to a pattern, and therefore generated by the pattern object rather than directly by the user.
If the matcher had a constructor that took a pattern, the matcher’s constructor might have had to access non-public fields of the pattern object.
Another potential advantage of this approach (compared to direct construction) is that it is in principle possible to provide different matching engines transparently to the user by instantiating different subtypes of Pattern and Matcher behind the scenes. For example, suppose that you had different matcher implementations for regular expressions that match a fixed-length string (e.g., no wildcards), and for regular expressions that contain an asterisk or a plus, and that there was a performance difference. That being said, it doesn’t seem like this actually takes place since the Matcher is defined as a final class, though it is likely that the internals are closely bounded to the pattern.