Java constructor example

Hey guys!! Welcome to flower brackets blog. Today we are going to learn java constructor example.

java constructor example

What is a constructor?

Basically constructor in java is a method, rather a special method to initialize an object.

Here’s the example of constructor in java,

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

   public Employee(String name, int age)
   {
      this.name = name;
      this.age = age;
   }   
}

In the example above you can see “Employee” class, it has two attributes name and age.

It has one “Employee” constructor which accepts name and age. Using this constructor we can create “Employee” object.

Also read – learn constructor in java

So the definition of constructor is, a class contains constructors that are invoked to create objects from the class.

Constructor name should match with the class name. Constructor declarations looks like method declaration except the constructor use the name of the class and constructor has no return type.

Let’s see an example now,

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

   public Employee(String name, int age)
   {
      this.name = name;
      this.age = age;
   }
   
   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      this.name = name;
   }

   public int getAge()
   {
      return age;
   }

   public void setAge(int age)
   {
      this.age = age;
   }

   public static void main(String args[])
   {
      Employee samEmployee = new Employee("Sam", 23);
      System.out.println("Employee Name : " + samEmployee.getName());
      System.out.println("Employee Age : " + samEmployee.getAge());
      System.out.println("----------------------------------");
      Employee benEmployee = new Employee("Ben", 28);
      System.out.println("Employee Name : " + benEmployee.getName());
      System.out.println("Employee Age : " + benEmployee.getAge());
   }
}

Output:

Employee Name : Sam
Employee Age : 23

--------------------------------------

Employee Name : Ben
Employee Age : 28


Related Posts