X
    Categories: java

Java Constructor | constructor example

 

Constructor is used to initialize objects when they are created and memory is allocated to the object.Every class has a constructor even if you specified or not.

Name of the java constructor is same as the class name and there is no return type for them.

 

What is a return type???

When you create any method you need to specify a return type in object oriented programming where as in procedure oriented programming like c language you need not specify mandatory return type as default return type is  int.

But in java you need to specify a return type in method creation.But for a java constructor is also like a method without any return type.

 

Method declaration and return type are as follows

 

When you don’t need a return type specify void

void abc(){

}

 

When you need String return type

String abc(){

}

 

same when you need int return type

int abc(){

}

 

like wise for every method specify a return type based on requirement.

 

Java Constructor :

As we discussed earlier a constructor is used to initialize object when created

There are two types of constructor’s

  1. Default Constructor
  2. Parameterized Constructor

 

Default Constructor:

Let’s see how consider a class Employee

Employee emp = new Employee();

Here emp is the object

new is used to create a object

Employee() is the Constructor

 

class Employee {

    String name;
    String empid;

    Employee() {
        name = "abc";
        empid = "emp01";
    }

}

 

Now call the default constructor

public static void main(String args[]) {

    Employee emp = new Employee();
    System.out.println(emp.name);
}

 

 

class Employee {

    String name;

    Employee() {
        name = "abc";
    }

    public static void main(String args[]) {

        Employee emp = new Employee();
        System.out.println(emp.name);
    }

}

 

Parameterized Constructor :

Parameterized constructor will have parameters declared in constructor.

Let’s see how it works

For you understanding

 

Default Constructor

Employee() {
    name = "abhi";
}

 

Parametrized Constructor

Employee(String name,String empid) {
    this.name = name;
    this.empid = empid;
}

 

This time we will call parametrized constructor

public static void main(String args[]) {

    Employee emp = new Employee("abhi","emp01");
    System.out.println(emp.name);

}

 

class Employee {

    String name;
    String empid;

    Employee() {
        name = "abhi";
    }

    Employee(String name,String empid) {
        this.name = name;
        this.empid = empid;
    }

    public static void main(String args[]) {

        Employee emp = new Employee("abhi","emp01");
        System.out.println(emp.name);
        System.out.printn(emp.empid);

    }
}

 

 

 

 

abhishek:
Related Post

This website uses cookies.