Constructor in java



Constructor is a member method. Constructor is used to initialize the objects. When we create an object for class, the constructor will be call automatically.


The constructor name should be same as the class name. It's return nothing. We can provoid initial variable in Constructor.






Types of Constructor



  1. Default constructor
  2. Parameterized constructor







1. Default constructor



Default constructor does not have any parameters.




Example-1
class Constructor
{
      public Constructor()
      {
            System.out.print("This is constructor");
      }
}

public class Main
{
      public static void main(String[] args) 
      {
            Constructor obj = new Constructor();
      }
}


Output



This is constructor









2. Parameterized constructor



Parameterized constructor consists of parameters.




Example-1
class Constructor
{
      public Constructor(int n)
      {
            System.out.print(n);
      }
}

public class Main
{
      public static void main(String[] args) 
      {
            Constructor obj = new Constructor(7);
      }
}


Output



7









Example-2
class Constructor
{
      public Constructor(int n,String name)
      {
            System.out.print(name+" : "+n);
      }
}

public class Main
{
      public static void main(String[] args) 
      {
            Constructor obj = new Constructor(7,"jack");
      }
}


Output



jack : 7