Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
No edit summary
No edit summary
Line 1:
In [[object-oriented programming]], a '''constructor''' (sometimes shorted to '''ctor''') in a class is a special block of statements called when an object is declared (statically constructed, possible in C++ but not in Java and other OO languages) or dinamically constructed trough the new keyword. A constructor is similar to [[method (computer science)|class methods]], but it is not a special kind of method, because it never has a return type, it's not inherited, and usually has different rules for modifiers. Constructors are simply special block of statements that are called automatically uponat the moment of creation of an [[object (computer science)|object]] (instance of a class). They are often distinguished by having the same name as the declaring [[class (computer science)|class]]. Its mainTheir purposeresponsibility is to pre-define the object's [[data member]]s 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.
 
=== [[Java programming language|Java]] ===
Line 6:
 
*Constructors never have a return type.
*Constructors can't be directly invoked ("new" keyword must be used)
*Constructors can't be overridden, nor they are inherited
*Constructors shouldn't call other overridable methods