What is Constructor in JAVA

Constructor in JAVA
              In our real life, building constructor is the person who constructs the building. Likewise constructor in JAVA is also used to construct the object i.e. initialize the newly created object. Constructor is called while creating an object. It is called while creating object using new() operator.
Constructor is  same  like method with the same name as class name but  no return type.

Types of constructor 
            i] Default constructor
           ii] Parametrized constructor.

Default Constructor:
             It is not mandatory to define a constructor in a class. When the constructor is not defined, Java compiler  will create default constructor and the values are assigned with default values.
             int value is assigned with 0. String value is assigned with null.

              SampleClass exp= new SampleClass()                                                                                              
             If the SampleClass is not defined,java compiler will provide  default constructor and assigned
with default values.

Parametrized Constructor:
            If the constructor have parameters, then it is called parametrized constructor.

 SampleClass exp=  new SampleClass(name)   //  Parametrized constructor
         
            If the parameters are passed during object creation, it is mandatory to define the parameterized constructor in the class

Example:
Default constructor:

class SampleClass{
int a;

//Default constructor
SampleClass(){
a=10;
}

public static void main(String args[]){    
SampleClass exp=new SampleClass();   // creating the object
exp.add();                            //  Calling the add method to
}

//Let us create a add function to do addition operation
void  add(){

int b=a+5;
System.out.println("the value of b is "+b);
}
}


output :the value of b is 15


If the constructor is not explicitly defined,

class SampleClass{
    int a;

public static void main(String args[]){    
SampleClass exp=new SampleClass();   // creating the object
exp.add();                            //  Calling the add method to
}

//Let us create a add function to do addition operation
void  add(){

int b=a+5;
System.out.println("the value of b is "+b);
}
}

output:the value of b is 5  //  a is assigned with the value 10


Parametrized contructor:


class SampleClass{
int a;

SampleClass(int value){
a=value;
}

public static void main(String args[]){    
SampleClass exp=new SampleClass(10);   // creating the object
exp.add();                            //  Calling the add method to
}

//Let us create a add function to do addition operation
void  add(){

int b=a+5;
System.out.println("the value of b is "+b);
}
}


output :the value of b is 15

                                          


Previous
Next Post »