As we know Java is an object oriented language. Everything is objects in Java. We also know that objects have something (instance variables / fields) and do something (methods).
Constructor in Java
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. The constructor actually returns the current class instance (You cannot use return type yet it returns a value). There are basically two rules defined for the constructor.
1)Constructor name must be same as its class name 2)Constructor must have no explicit return type
Types of constructors
1)Default constructor (no-arg constructor)
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
2)Parameterized constructor
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}