constructors

8
Constructors

Upload: yaswanth-babu

Post on 19-Jul-2015

34 views

Category:

Education


1 download

TRANSCRIPT

Page 1: Constructors

Constructors

Page 2: Constructors

Constructor is a special method of a class which will invokeautomatically whenever instance or object of class is created.

Constructor name should be same as class name. If we want tocreate constructor in a class we need to create a constructormethod name same as class name.

ex:

<AccessModifier/static/Nothing> <ClassName>(){

//Initialization}

Page 3: Constructors

class can have any number of constructors and constructorsdon’t have any return type, not even void

Constructors are responsible for object initialization and memoryallocation of its class.

There is always at least one constructor in every class.

Page 4: Constructors

Types of Constructors1. Default Constructor2. Parameterless Constructor3. Parameterized Constructor4. Copy Constructor5. Private Constructor6. Static Constructor

Page 5: Constructors

Default Constructor:Default constructor will be added by compiler, if we do not

write any constructor in a class. Default constructor does not have anyparameters .

Parameterless Constructor:If we do not write any parameters in a constructor is called as

parameterless constructor.

Parameterized Constructor:A constructor with at least one parameter is called as

parameterized constructor.

Page 6: Constructors

Copy Constructor:

A parameterized constructor that contains a parameter ofsame class type is called as copy constructor.

Main purpose of copy constructor is to initialize new instanceto the values of an existing instance.

Ex:

<AccessModifier/Nothing> <ClassName>(ClassName cn){}

Page 7: Constructors

Private Constructor:

A private constructor is a special instance constructor.

The main purpose of creating private constructor is used torestrict the class from being instantiated.

Ex:

<private/Nothing> <ClassName>(){}

Page 8: Constructors

Static Constructor:

When we declared constructor as static it will be invoked onlyonce for any number of instances of the class.

Static constructor is used to initialize static fields of the class andto write the code that needs to be executed only once.

Static constructor will not accept any parameters because it isautomatically called by CLR.

Static constructor will not have any access modifiers. Static constructor will execute automatically whenever we create

first instance of class.

Only one static constructor will allowed.