Wednesday 28 August 2013

Constructor

Constructor is used to provide value to the object.Constructor is called at the time of object creation.
To initialised  the object we use constructors.

2 types of constructor:-
1-NO args constructor
2-Argumented Constructor

Conditions for the constructor:-
-the name of the constructor should be same as the class name.
-constructor doesn't contain any return type.

Example:- No Args constructor


if you create 2 objects constructor will call 2 times. constructor calling is depend on the object creation.

Example
                                            


Argumented Constructor:-it is used to provide some initial value to the object.Constructor should have a unique signature.Two constructors doesn't have the same signature or parameter.

Example:-

here we initialise 20 into j through constructor.

Constructor Overloading:-creating  more than one constructor in one class known as constructor overloading always remember ,Constructor should have a unique signature.

Example:-


first we didn't pass any argument at the time of object creation so it call the conctructor with no args and second time we pass one argument so it call argumented constructor.

Example 2


here we take constructor with 2 arguments so we must  pass 2 arguments at the time of object creation.

Use of this() in constructor:- it is used to call one constructor from another constructor but this() should be the first statement in the constructor.if you place this() in 2  or 3 or anywhere except as a 1st  statement you will get compile time error..

Example:-

                                                       

 in the above program we call no arg constructor using this() statement  from the argumented constructor so we didn't  pass any argument in the this();




in tha above program we call the argumented constructor from the no argumented constructor .argumented constructor contains two parameter so we pass 2 values in this keyword.

Difference between Constructor and Method:-

  1. Constructor does not have any return type but method have or does not have return type.
  2. Constructor name should be same as the class name but for method we can give any name.
  3. The java compiler provides default constructor but it does not provide default method.
  4. Constructor is invoked implicitly but method is invoked explicitly.




No comments :

Post a Comment