Example of Constructor in Java

In this tutorial, we will write a constructor program in java. Before that, you should have knowledge on the following topic in Java.


Constructor program in Java

Basic Example for displaying the default values in Java:

 public class Employee
 {
   int id;
   String name;
   int age;

   //Method for Displaying default values  
   void display()
   {
     System.out.println(id + " " + name + " " + age);
   }

   public static void main(String args[])
   {
     //creating objects  
     Employee e1 = new Employee();
     Employee e2 = new Employee();

     e1.display();
     e2.display();
   }
 }

Output:

0 null 0
0 null 0


Example of Parameterized Constructor in Java:

public class Employee
{
  int id;
  String name;
  int age;

  //parameterized constructor  
  Employee(int i, String n, int a)
  {
    id = i;
    name = n;
    age = a;
  }

  //display the values  
  void display()
  {
    System.out.println(id + " " + name + " " + age);
  }

  public static void main(String args[])
  {
    //creating objects and passing values  
    Employee e1 = new Employee(101, "John", 30);
    Employee e2 = new Employee(105, "Ron", 32);

    //calling display method 
    e1.display();
    e2.display();
  }
}

Output:

101 John 30
105 Ron 32