Constructor

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 6

Types of java constructors

• There are two types of constructors in java:


– Default constructor (no-arg constructor)
– Parameterized constructor
• A constructor is called "Default Constructor" when it doesn't
have any parameter.
<class_name>()
{
……………………
}  
Example of default constructor
class Student
{  
     int id;  
     String name;  
      
    Student()
{  
     id = 10;  
     name = ”Anu”;  
     }  
    void display()
{
System.out.println(id+" "+name);
}  
   
    public static void main(String args[])
{  
     Student s1 = new Student();  
       s1.display();  
    
    }  
}  
Java parameterized constructor
• A constructor which has a specific number of parameters is called parameterized constructor.
class Student
{  
     int id;  
     String name;  
      
    Student((int i,String n)
{  
      id = i;      
name = n;     
 }  
    void display()
{
System.out.println(id+" "+name);
}  
   
    public static void main(String args[])
{  
     Student s1 = new Student(111,"Karan");  
       s1.display();  
    
    }  
}  
Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like copy
class Student constructor in C++.
{  
     int id;  
     String name;       
    Student((int i,String n)
{  
      id = i;      
name = n;     
 }  

Student(Student s)
{       id = s.id;     
 name =s.name;    
  }  
    void display()
{
System.out.println(id+" "+name);
}  
    public static void main(String args[])
{  
     Student s1 = new Student(111,"Karan");  
Student s2 = new Student (s1);  
       s1.display();  
      s2.display();  
    }  
}  
Constructor Overloading in Java
Constructor overloading in Java is a technique of having more than one constructor with different parameter lists.
class Student
{  
     int id;  
     String name;  
         Student()
{  
      id = 10;      
name = ”anu”;     
 }  

    Student((int i,String n)
{  
      id = i;      
name = n;     
 }  
    void display()
{
System.out.println(id+" "+name);
}  
   
    public static void main(String args[])
{  
     Student s1 = new Student();  
  Student  s2= new Student(111,"Karan");  
       s1.display();    
s2.display();    
 }  
}  

You might also like