CONSTRUCTOR by G Krishna Chauhan

Constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor :There are basically two rules defined for the constructor.
  1. Constructor name must be same as its class name.
  2. Constructor must have no explicit return type.
Types of java constructors: There are two types of constructors:
  1. Default constructor (no-arg constructor).
  2. Parameterized constructor.
Java Default Constructor: A constructor that have no parameter is known as default constructor.

Program Example:

class xyz1
{  
xyz1()
{
System.out.println("xyz is created");
}  
public static void main(String args[])
{  

xyz1 b=new xyz1();  
}  
}  

Java parameterized constructor:

A constructor that have parameters is known as parameterized constructor. Parameterized constructor is used to provide different values to the distinct objects.


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");  
Student s2 = new Student(222,"Aryan");  
s1.display();  
s2.display();  
}  
}  


Constructor Overloading in Java:

Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.


class xyz 
{
 int a,b,i;
 xyz()
 {
  System.out.println("the value of a ->"+a);
  System.out.println("the value of a ->"+b);
 }
 xyz(int a,int b)
 {
  int c=0;
  c=a+b;
  System.out.println("the value of a ->"+c);
 }
 xyz(int i)
 {
  i=i+1;
  System.out.println("the value of a ->"+i);
 } 
}

class test
{
 public static void main(String arg[])
 {
 xyz x1=new xyz();
 xyz x2=new xyz(6,9);
 xyz x3=new xyz(1);
 }
}


Difference between constructor and method in java:


There are many differences between constructors and methods. They are given below.



No comments:

Post a Comment