The Constructor is like a method having the same name as the class name, without a return type and it is automatically called when an instance is created with appropriate arguments. The main purpose of a Constructor is to initialize the class variables.
The JVM will give a default Constructor only if there is no parameterized constructor in the class.
Without Constructor :
class Student1
{
String name;
int id;
void show()
{
System.out.println("Your Name = "+name);
System.out.println("Your ID = "+id);
}
}
class Constructor1
{
public static void main(String args[])
{
Student1 n=new Student1();
n.name="Maya";
n.id=100;
n.show();
}
}
With Constructor:
class Student2
{
String name;
int id;
void show()
{
System.out.println("Your Name = "+name);
System.out.println("Your ID = "+id);
}
Student2(String a, int b)
{
name = a;
id = b;
}
}
class Constructor2
{
public static void main(String args[])
{
Student2 n2 = new Student2(“Maya”,100)
n2.show();
Student2 y = new Student2();
}
}
Student2 y gives an error couse there is no
constructor without parameter