To limit instantiation of a class to your own factory method or when there are only static methods use a private constructor. If a class has a private constructor and no public constructors, then other classes cannot create instances of this class. If you don't use an access modifier before the constructor it will be private by default.
Static constructors are used to initialize static data within a class or perform an action that only needs to be executed once during the lifetime of the program. A static constructor cannot have access modifiers or parameters. Static constructors are called automatically by the virtual machine to initialize the class. Example of these concepts are given in class DNAAlphabet.cs below.
The private constructor for Adenine prevents multiple instantiation of the class from outside. A private static
instance is given out to consuming code that wants an instance. Adenine demonstrates invocation of
the parent constructor using the base keyword. The DNAAlphabet class has a static
constructor, which gets the singleton Adenine instance. This pattern
(the singleton pattern) can be used with a large sequence of DNA symbols that actually only refer to four
Symbol object for Adenine, Guanine, Cytosine, and Thymine.
Running the program produces the output:
Constants should be used for values that do not change. The Adenine class above demonstrates the
const keyword to define the constants NAME and ANNOTATION.
There are no user comments.
Please send ideas and opinions by email at alexamies@gmail.com.