The Significance of Using Constructor In Java

Posted By : Jatin Singh | 31-Oct-2020

constructor in java

 

 

Constructor:-

A constructor is a non-static member function of a class declared with the same name as the name of the class. It is a nor return type function and a constructor is used to initialize the objects of class.

Non-Static function:-In java if we define a function without using any keyword then by default it is a non-static function.

 Syntax:-

class Documentation {

   Documentation () {

   }

}

 Explanation of above syntax:- A class is created with name "Documentation" and having a constructor "Documentation" with same name as class name and it is a non-static function.

 

Key Features:-

 1- When no constructor is defined in the program then the compiler provides the default constructor for the class.

2- Constructor can be parameterized.

3- Constructor can be overloaded which mean we can define more than one constructor in a class.

 

Types:-

  1. Parameterized Constructor 
  2. Non-Parameterized Constructor

 Parameterized Constructor:-

    A constructor defined by passing arguments then is known as a parameterized constructor.

 Example:-

class Constructor {

   int a;

   Constructor(int a ) { //Parameterized constructor

      a = i;

   }

public class Cons {

   public static void main(String args[]) {

      Constructor c1 = new Constructor();

      c1.Constructor(55)

      System.out.println(a);

   }

 

Explanation of above code:-

  A class "Constructor" is created and having a parameterized constructor define with same name as the name of class "Constructor(int a)" where "int a" is a parameter so, it is called as parameterized constructor and in class "Cons" a constructor is called with the help of object "c1" of class "Constructor".

 Output:-55

 

Non-Parameterized Constructor:-

    A constructor defined without passing argument is then known as a non-parameterized constructor.

 Example:-

 Class Rectangle{

  private int l,b,h;

  public Rectangle() { //Non-Parameterized Constructor

  l=10;

  b=10;

  h=10;

  }

}

public class Construct {

   public static void main(String args[]) {

      Rectangle b1 = new Rectangle();

      b1.Box()

      System.out.println("Length of box : "+l);

      System.out.println("Breadth of box : "+b);

      System.out.println("Height of box : "+h);

   }

 Output:-

Length of box : 10

Breadth of box : 10

Height of box : 10

 

We, at Oodles ERP, provide end-to-end ERP development services to overcome complex enterprise challenges and streamline inbound/outbound operations. Our custom ERP software development services enhance your business productivity and improve operational efficiency. For more information, contact us at [email protected]

 

 

 


 


Please remove URL from text

Comment is required

Sending message..
Connect with us