Home > DeveloperSection > Blogs > Constructor in java

Constructor in java

Java Java 
0 Comment(s)
 786  View(s)
Rate this:
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation.It constructs the value i.e. provides data for the object that is why it is known as constructor.
Rules for creating java constructor:
>Constructor name must be same as its class name.
>Constructor must have no explicit return type.

There are two types of constructors:

Default constructor (no-arg constructor)

Parameterized constructor

java constructor

Constructor that have  no parameter is known as default parameter.
  1. <class_name>(){}  
  2. e.g. of default constructor, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
    1. class Bike1{  
    2. Bike1(){System.out.println("Bike is created");}  
    3. public static void main(String args[]){  
    4. Bike1 b=new Bike1();  
    5. }  
    6. }  
  3. Bike is created.

A constructor that have parameter is known as parameterized constructor.
 example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
  1. class Student4{  
  2.     int id;  
  3.     String name;  
  5.     Student4(int i,String n){  
  6.     id = i;  
  7.     name = n;  
  8.     }  
  9.     void display(){System.out.println(id+" "+name);}  
  11.     public static void main(String args[]){  
  12.     Student4 s1 = new Student4(111,"Karan");  
  13.     Student4 s2 = new Student4(222,"Aryan");  
  14.     s1.display();  
  15.     s2.display();  
  16.    } 
  17. }  
  18. Output:
111 Karan
222 Aryan

Don't want to miss updates? Please click the below button!

Follow MindStick