Constructor (object-oriented programming): Difference between revisions

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.
 
<math>Insert formula here</math>=== [[Java programming language|Java]] ===
==== Example ====
public class Example
Line 31:
End Class
 
==Constructors Simplified (with [[pseudocode]])==
 
Constructors existare withinalways part of the implementation of classes. Classes A class (in programming) language referrefers to a generic specfication whichof arethe notgeneral real,characteristics butof justthe aset prototype.of Aobjects simplethat analogyare tomembers understandingof constructorsthe wouldclass berather to imaginethan the followingspecific scenerios:characteristics Compareof classany inobject thisat caseall. to aA simple analogy follows. Consider the set (or class, using its generic meaning) of students at some school. Thus we have
 
<pre>class StudentsStudent {
===[[Pseudocode]]===
<pre>class Students{
// refers to the class of students
// ... more omitted ...
}</pre>
 
However, the class Students<code>Student</code> is just a generic prototype of what a student should be. Let'sTo analyseuse this fromit, the positionprogrammer ofcreates theeach ISstudent manageras shouldan the''object'' schoolor wants''instance'' toof createthe aclass. database ofThis everyobject student inis a computerisedreal database.quantity Let'sof assumedata in thismemory casewhose thatsize, theylayout, wantcharacteristics, and (to createsome eachextent) studentbehavior asare andetermined object.by Thusthe theyclass applydefinition. the codeThe belowusual toway createof acreating prototypeobjects or "mould"is to createcall ana instance of the class Studentsconstructor (ieclasses tomay createin ageneral realhave studentmany underindependent the class Studentsconstructors). These mouldsFor are often used as constructors.example,
 
<pre>class StudentsStudent {
===[[Pseudocode]]===
StudentsStudent (String studentName, charString sex, String Address, int ID) {
 
// ... 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);
} </pre>
 
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:
Once done, these specific students that we create using the above are also known as instances of the class Students. To create these instances, we use constructors within a class. A constructor is the same as a mould defining the specifications of the student mould we describe above. It defines the type of student, with variables that distinguishes it from other instances. Constructors are normally named the same as their class name. Thus, to create a constructor of a student in a class with some predefined variables, we do the following:
 
</pre>
Every student will have characteristics that distinguishes them. For example, students have their individual Name, Sex, Address, Unique ID etc. We want to create a prototype, or "mould" for these students such that we can construct each student's profile using simple code like Students("John","M","Dover Road", 12345). If the analyst wants to print out the information for its students, it can use the following code;
<pre> print(Studentsjohn.studentName); // output "John Doe", the internal data
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]].
===[[Pseudocode]]===
<pre> print(Students.studentName) // output "John"
</pre>
 
==See also==