Monday, 20 January 2014

CONSTRUCTORS IN JAVA


A constructor initializes an object immediateily upon creation.It has the same name as the class in which it resides and is syntactically similar to a method.Once defined, the constructor is automatically called immediately after the object is created,before the new operator completes.Constructors look a little strange because they have no return type ,not even void.Attributes of an object may be available when creating objects if no attribute is available then default constructor is called, also some of the attributes may be known initially.



Example1 for initializing constructor

class Programming
 {
Programming()  //constructor method
 {
   System.out.println("Constructor method called.");
  }
public static void main(String[] args)
 {
 Programming object = new Programming(); //creating object
 }
}

This would produce the following results

Constructor method called

This code is the simplest example of constructor, we create class Programming and create an object, constructor is called when object is created. As you can see in output "Constructor method called." is printed


Parameterized Constructors:

Constructors that can take arguments are termed as parameterized constructors.When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function.Constructor can take any number of arguments.Arguments can be any type, that is integer,character,etc..

Example2 for parameterized constructor:


class Rectangle
 {
  int length;
  int breadth;
  Rectangle(int len,int bre)
  {
      length = len;
      breadth = bre;
    }
}
class RectangleDemo
{
  public static void main(String args[])
    {
   Rectangle r1=new Rectangle(10,30);  // Parameterized constructor
  system.out.println("Length of the rectangle is:" + r1.length);
  system.out.println("Breadth of the rectangle is:" + r1.breadth);
    }
}




This would produce the following results

Length of the rectangle is:10Breadth of the rectangle is:30

 Here Rectangle r1=new Rectangle(10,30);  this is parameterized constructor taking argument.This arguments are used for any purpose inside constructor Body.




















No comments :

Post a Comment