Content deleted Content added
grammar? |
rewrite pseudocode section; copyedit |
||
Line 1:
In [[object-oriented programming]], a '''constructor''' in a class is a special [[method (computer science)|method]] (function) that can be used to create objects of the class and never has a return type. Constructors are special [[method (computer science)|instance methods]] that are called automatically upon the creation of an [[object (computer science)|object]] (instance of a class). They are often distinguished by having the same name as the [[class (computer science)|class]] of the object they're associated with. Its main purpose is to pre-define the object's [[data member|data members]] and to establish the [[invariant (computer science)|invariant]] of the class, failing if the invariant isn't valid. A properly written constructor will leave the [[object (computer science)|object]] in a 'valid' state.
==== Example ====
public class Example
Line 31:
End Class
==Constructors Simplified (with [[pseudocode]])==
Constructors
▲<pre>class Students{
// refers to the class of students
// ... more omitted ...
}</pre>
However, the class
// ... storage of input data and other internal fields here ...
▲<pre>class Students{
}
// ... more omitted ...
▲ Students (String studentName, char sex, String Address, int ID) {
}
// elsewhere:
} </pre>▼
Student john = Student("John Doe", "male", "under the sea", 42);
It is up to the class to decide what to do with the information provided (storing it within the new object is very common, but it might be stored in an entirely different format, passed to other constructors or functions and then forgotten, or even disregarded altogether). The constructed object is persistent, and (depending on the class) may be augmented, examined, or modified in ways related or not to the constructor:
print(john.getFirstName()); // object calculates just "John", which is printed
john.addNickName("Johnny"); // object remembers this
</pre>
Here it is assumed that the class provides the <code>studentName</code> variable and the <code>getFirstName()</code> and <code>addNickName()</code> functions, and that the variable is simply assigned the value of the first argument to the constructor. Note that this code does not explicitly mention the class <code>Student</code>; it is known that the variable <code>john</code> is an instance of the class, so the elements of the variable are understood to be members of the same class. This implicit specification is a powerful mnemonic, although it is not fundamentally more powerful than [[function overloading]].
▲<pre> print(Students.studentName) // output "John"
▲</pre>
==See also==
|