Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
MTSbot~enwiki (talk | contribs)
m robot Modifying: fr
Constructors are NOT methods
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 or explicitally constructed trough the new keyword, depending by the language. A constructor is similar to [[method (computer science)|methodclass methods]], (function)but calledit whenis annot objecta isspecial declaredkind of method: andit never has a return type, it's not inherited, has different rules for modifiers. Constructors are special [[methodblock (computerof science)|instance methods]]statements 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]]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]] ===
 
Some of the differences between Java methods and constructors:
 
*Constructors never have a return type.
*Constructors can't be overridden, nor they are inherited
*Constructors shouldn't call other overridable methods
*Constructors can't be synchronized
*Constructors are always executed by the same thread
*Constructors can't be final
*Constructors can't be abstract
 
==== Example ====
public class Example
Line 90 ⟶ 101:
==References==
* [[Bjarne Stroustrup]]: ''The C++ Programming Language'', Addison-Wesley, ISBN 0-201-70073-5
* [[James Gosling]]: ''The Java Programming Language'', Addison-Wesley, ISBN 0-321-34980-6
 
[[Category:Programming constructs]]