Java Constructor

constructor in java

Java Constructor are special methods invoked when an object is created and are used to initialize them.

A constructor can be used to provide initial values for object attributes.

The constructor is called when you create an object using the new keyword.


There are two types of constructors in Java:

→ default constructor
→ parameterized constructor


Rules for creating Java constructor:

There are two rules defined for the constructor.

  • Constructor name must be the same as its class name
  • A Constructor must have no explicit return type
  • A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors:

Default Constructor:

A constructor is called “Default Constructor” when it doesn’t have any parameter.

Syntax of default constructor:

<class_name>(){}

Example of default constructor:

// Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println(“Bike is created”);}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Parameterized Constructor:

A constructor which has a specific number of parameters is called a parameterized constructor.

Example :

//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
    int id;
    String name;
    //creating a parameterized constructor
    Student4(int i,String n){
    id = i;
    name = n;
    }
    //method to display the values
    void display(){System.out.println(id+” “+name);}
    public static void main(String args[]){
    //creating objects and passing values
    Student4 s1 = new Student4(111,”Karan”);
    Student4 s2 = new Student4(222,”Aryan”);
    //calling method to display the values of object
    s1.display();
    s2.display();
   }
}


Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *