Constructor can be defined as a block similar to a method, having same name as that of class name..

Example Code for Constructor:

public class Student {

public Student{ 

}

public static void main(String[] args){

// so here what we have to do is just create an object like

Student st = new Student(); // and that’s all, here we don’t need to write any reference like

st.Student();

}

}

Watch the Video On Constructors in Java, For Live programming:

Use of Constructor in Java:

  • Constructor can be defined as a block similar to a method, having same name as that of class name..
  • Constructor have doesn’t any return type.
  • Modifiers  which we can use for constructors are public, protected, default and private only. It can’t be abstract, static, final and synchronized.
  • how we run constructor in java? So constructor executes automatically, when we create an object.  we don’t need to execute like a method.

Types of Constructor in Java:

  1. Default Constructor
  2. Parameterized Constructor

1. Default Constructor:  Also we called it as no-arg constructor,arg simply means arguments. A constructor is called as default constructor when it doesn’t have any parameter. The syntax of default constructor is like: <class_name>(){}

Program for Default Constructor:

class Bike{

                Bike(){

                    System.out.println(“Bike is perfect”);

                }

public static void main(String[] args){

Bike b = new Bike();

}

}

Output: Bike is perfect

The default constructor is used to provide the default values to the object which is 0, null, etc.. which is depending on the type.

class Bike{

int mileage;

String model;

void Bike1(){

            System.out.println(mileage+” “+model);

                }

public static void main(String[] args){

Bike b = new Bike();

b.Bike1();

}

}

Output: 0 null

The compiler here is provides a default constructor. As you can see at the output 0 and null which is provided by default constructor.

1. Parameterized Constructor:

Parameterized Constructors are basically used to provide same and different values to distinct objects.

Program for Parameterized Constructor:

class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}

void display(){
System.out.println(id+” “+name);
}

public static void main(String args[]){
Student s1 = new Student(101,”Java”);
Student s2 = new Student(202,”Android”);
s1.display();
s2.display();
}
}

Output: 101 Java and 202 Android

Connect with us: