Constructor in Java
- It is a special kind of method which is used to initialize the object.
- A block of codes same as the method.
- It is called when an instance of the class is created.
Types of Constructor
- Default constructor (no-argument)
- Parameterized constructor (argument)
Default Constructor
It doesn't have any parameter.
Example :
class Student
{
//creating a default constructor
Student ()
{
System.out.println("Student is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Student s=new Student ();
}
}
Output :
Student is created
Parameterized Constructor
It has a specific number of parameters.
Example :
class Student
{
String name;
int age;
//creating one arg constructor
Student(String n)
{
name = n;
}
//creating two arg constructor
Student(String n)
{
name = n;
age=a;
}
void display()
{
System.out.println(name+" "+age);
}
public static void main(String args[]){
Student s1 = new Student("Karan");
Student s2 = new Student("Aryan",15);
s1.display();
s2.display();
}
}
Output :
Karan 0
Aryan 15
0 Comments