Others noted that constructors may have access modifiers; an aspect that has not yet been mentioned is that aspect modifiers on the designer control two very different aspects of the design, but do not allow them to be controlled separately:
- Who is allowed to instantiate
ClassName and which constructors are allowed to use them. - Who is allowed to create
ClassName extensions and which constructors are allowed to use them.
Both Java and .NET require that the answers to these two questions match; if the class is not final (or sealed ) and allows the constructor to use external code to create new instances, then the external code will also have complete freedom to use the same constructor to create derived types.
In many cases, it may be appropriate for the class to have only package-private ( internal ) constructors, but to expose public methods that return new instances. This approach can be used if you are developing a type such as String from scratch; a package that includes String can define it as an abstract type, but includes specific derived types, such as AsciiString and UCS16String , which store their contents as byte[] and Char[] respectively; methods that return String can then return one of the derivatives, depending on whether the strings contain characters outside the ASCII range. If neither String nor any derived types expose any constructors outside their package, and all derived types inside the package will behave like a string, they are expected to behave, then code that receives a reference of type String can expect it to be behave wisely as a string (for example, ensuring that any observation of its value remains true forever). However, using constructors outside the package would allow derived types to behave in a strange and bizarre way (for example, changing their contents after they have been validated and validated).
From a syntactic point of view, the ability to say Fnord foo = new Fnord(123); a little nicer than saying Fnord foo = Fnord.Create(123); , but the Fnord class, which requires the latest syntax, can significantly improve control over the process of creating an object.
supercat Jun 23 '15 at 17:19 2015-06-23 17:19
source share