About me

Gladson A
Software Engineer,Chennai.

Translate

Pages

Saturday 30 June 2012

Constructor in JAVA


Constructor in JAVA


-Constructor initialize an object Of a class immediately upon creation.


-JAVA creates constructor call for every object that is created.


-When you create a new instance (a new object) of a class using the new keyword, a constructor for that class is called.

program 1:

public class contest {

contest()
{

System.out.print("this is constructor");
}

public static void main(String[] a)

{
constortest c=new constortest();

}


}

output:

this is constructor

-Constructors are similar to methods, but with some important differences.



1.Constructor name is class name. A constructors must have the same name as the class its in.


2.Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created.


3.If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans).


4.Constructor cannot return values.


5.cannot specify return type (not even void).

program 2:

public class constructor {

static int t=9;

public constructor(double y,int e)

{
System.out.println("these are two parameterized constructor:"+y+"   "+e);
}

public constructor(constructor e)

{
t=3;
System.out.println("this is parameterizer constructor passing object:"+t);
}

public constructor(int dd)

{
t=2;

System.out.println("this is parameterized constructor:"+t);

}

public constructor()

{
t=1;
System.out.println("this is parameterless constructor:"+t);
}

public static void main(String[] b)

{

constructor c1=new constructor();
constructor c2=new constructor(t);
constructor c3=new constructor(c2);
constructor c4=new constructor(12.7,13);
System.out.println("main function test:"+t);
                constructor.fuc();
       constructor c5=new constructor();
       constructor.fuc();
}

public static void fuc()

{
System.out.println("sub function test:"+t);
}
}

output:

this is parameterless constructor:1
this is parameterized constructor:2
this is parameterizer constructor passing object:3
these are two parameterized constructor:12.7   13
main function test:3
sub function test:3
this is parameterless constructor:1
sub function test:1

(NOTE: Next is about calling constructor from a constructor using keywords this() and super())

                       Ask your Forums and Questions in the Comment box (mention your main Id).




0 comments:

Post a Comment