Tuesday, July 23, 2013

CONSTRUCTOR


Constructor is a special method, that initializes an object immediately upon creation this automatic initialization is performed through the use of constructor.

KEY POINTS ABOUT CONSTRUCTOR:
``````````````````````````````````````````````````````

  1. It should have same name as that of class.syantactically similar to a method
  2. once defined and automatically called immediately after allocating memory
  3. it does not have any return type.
TYPES OF CONSTRUCTOR:
``````````````````````````````````````
  • Default Constructor:
    • every class has its default constructor
    • if default constructor is not provided then compiler creates its own& initializes the default value.
    • no vales can be sent through default constructor
  • Parameterized Constructor:
    • Here values are set by specifically set as parameters.
    • This is for various initializing values. 
PROGRAM:
~~~~~~~~~

public class room
{
int width ;
int length;

room( )                         // DEFAULT CONSTRUCTOR
{
width=5;
length=5;
}

room ( int w,int l)            //PARAMETERIZED CONSTRUCTOR
{
width=w;
length=l;
}
int area( )
{
return(width*length);
}
}
 class room1
 {
public static void main(String a[])
{
room r=new room( );
room r1=new room( 50,50);//passing parameters to the parameterized constructor
r.width=10;   //assigning values to the variables
r.length=20;

int result=r.area( );
System.out.println("AREA IS: "+result);// calling method from another class using object
System.out.println("AREA IS: "+r1.area( ));
}

}

OUTPUT:
~~~~~~~~
AREA IS: 200                //by default constructor
AREA IS: 2500             //by parameterized constructor

No comments:

Post a Comment

Animated Social Gadget - Blogger And Wordpress Tips