JAVA Constructor
JAVA Constructor
The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.
Types of Java Constructors
class Student3{
int id;
String name;
//method to display the value of id and name
void display()
{ System.out.println(id+" "+name);
}
public static void main(String args[]){
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
} Output: 0 null
Constructor Overloading in Java
• In Java, a constructor is just like a method but without return type. It
can also be overloaded like Java methods.
• Constructor overloading in Java is a technique of having more than
one constructor with different parameter lists. They are arranged in a
way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list
and their type
Example of Constructor Overloading
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
void display(){System.out.println(id+" "+name+" "+age);}