Sie sind auf Seite 1von 2

In object-oriented programming, a constructor (sometimes shortened to ctor) in a class

is a special block of statements[dubious – discuss] called when an object is created, either when it
is declared (statically constructed on the stack, possible in C++ but not in Java and other
object-oriented languages) or when it is dynamically constructed on the heap through the
keyword "new".

A constructor is similar to an instance method, but it differs from a method in that it


never has an explicit return type, it is not inherited, and usually has different rules for
scope modifiers. Constructors are often distinguished by having the same name as the
declaring class. Their responsibility is to initialize the object's data members and to
establish the invariant of the class, failing if the invariant isn't valid. A properly written
constructor will leave the object in a valid state. Immutable objects must be initialized in
a constructor.

The term constructor is also used to denote one of the tags that wraps data in an algebraic
data type. This is a different usage than in this article.[dubious – discuss] For more information,
see algebraic data type.

In most languages, the constructor can be overloaded in that there can be more than one
constructor for a class, each having different parameters. Some languages take
consideration of some special types of constructors:

• default constructor - a constructor that can take no arguments


• copy constructor - a constructor that takes one argument of the type of the class
(or a reference thereof)

Example
public class Example
{
//definition of the constructor.
public Example()
{
this(1);
}

//overloading a constructor
public Example(int input)
{
data = input;
}

//declaration of instance variable(s).


private int data;
}

Object-oriented programming (OOP) is a programming paradigm that uses "objects" –


data structures consisting of datafields and methods together with their interactions – to
design applications and computer programs. Programming techniques may include
features such as information hiding, data abstraction, encapsulation, modularity,
polymorphism, and inheritance.

Class
Defines the abstract characteristics of a thing (object), including the thing's
characteristics (its attributes, fields or properties) and the thing's behaviors (the
things it can do, or methods, operations or features).

Abstraction
Abstraction is simplifying complex reality by modeling classes appropriate to the
problem, and working at the most appropriate level of inheritance for a given
aspect of the problem

Encapsulation
Encapsulation conceals the functional details of a class from objects that send
messages to it

Das könnte Ihnen auch gefallen