Constructors are used to initialize an object as soon as it is created. Every time an object is created using the „new‟ keyword, a constructor is invoked. If no constructor is defined in a class, java
compiler creates a default constructor. Constructors are similar to methods but with two differences, constructor has the same name as that of the class and it does not return any value. The types of
constructors are:
1. Default constructor: when the constructor is not defined in the program, the java compiler creates a constructor. Such a constructor is called a default constructor.
2. Parameterized constructor: Such constructor are defined in the program and consists of parameters. Such constructors can be used to create different objects with data members having different values.
class Student
{
int roll_no;
String name;
Student(int r, String n)
{
roll_no = r;
name=n;
}
void display()
{
System.out.println("Roll no is: "+roll_no);
System.out.println("Name is : "+name);
}
public static void main(String a[])
{
Student s = new Student(20,"ABC");
s.display();
}
}
3. No argument constructor- when the defined constructor in the program does not contain any arguments, then it is called no argument constructor.
0 Comments