Constructor in Java Programming

Concept of Constructor

constructor in Java is a block of code similar to a method it is called when an instance of an object is created. The key differences between a constructor and a method are given below:
  • A constructor doesn’t have a return type.
  • The name of the constructor must as same as the name of the class.
  • It is considered as the other member function of a class.
  • When an instance of the object is created it is called automatically.
  • It is called at the time of Object creation.

Syntax of the constructor:

   //This is the constructor
   public ClassName(Parameter list){
   Statement(s)...
   }

The public keyword in the constructor indicates that other classes can access the constructor. It can be defined under private and protected section but in such cases, the constructor is not available to the Non-member function. ClassName must be the same as the name of the class that contains the constructor.

The constructor allows you to provide initial values for class fields when you create the object. Suppose that you are creating a program to calculate the area of Rectangle and have a class named Rectangle that has fields named length and breadth. You can create a constructor for Any class:
public Rectangle(int l, int b)
{
       length = l;
       breadth = b;
}
         Then you create an instance of the Rectangle class by calling this constructor:
  Rectangle r = new Rectangle ("50", " 20");                                                                                                    
The new keyword here creates the object of class Rectangle and invokes the constructor to initialize this newly created object. A new Rectangle object for 50, 20 is created. 
            

Types of Constructor

The constructor function in a java programming language has two types and they are
1.  Parameterized Constructor

This type of Constructor can receive Parameters. Its syntax seems like:
  //This is the constructor
   public ClassName(parameter list){
   statement(s)...
   }

And the Syntax for  Creating and Initializing an Object is:

  ClassName ObjectName = new ClassName(Arguments);
              
              2. Non- Parameterized Constructor
              This type of Constructor cannot receive Parameters. Its syntax seems like:

 //This is the constructor
   public ClassName(){
   Statement(s)...
   }

                And the Syntax for Creating and Initializing an Object is:

 ClassName ObjectName = new ClassName();

Comments

Popular posts from this blog

Java Program to make a comparison between numbers

Java program using Scanner Class

Java program to print 'Hello World'