wellnwill Marathahalli Bangalore wellnwill Marathahalli Bangalore

Constructor in java


Constructor is a special type of method which is implicitly invoked by JVM at the time of object creation using new keyword. The purpose of constructor is to provide user define value to object level variable.


Characteristics of constructor

  • Constructor name must be same as its class name.
  • Constructor will be executed only once for each object of class.
  • Constructor does not have any return type even void also. Constructor with return type will be treated as normal method.
  • Constructor will be executed automatically just after the creation of object.
  • Static keyword is not used with constructor

Type of java constructor

There are two types of java constructor.

  • Default Constructor. i. zero argument constructor
  • User defined Constructor i. zero argument constructor ii. parameterized constructor

Default constructor

  • A constructor with no parameter (argument) is called default constructor.
  • The purpose of default constructor is to provide default value to the instance variable of the class.
  • Compiler is responsible to generate default constructor if we are not providing any constructor in the class.
  • Default constructor contains only one line of code i.e. super(). Call to super (super()) is used to call super class default constructor.
class Bulb
{  
     Bulb()
	 {
      super();
     }  
}

class Bulb
{  
   int watt;  
   String color;
   double price; 
 
 Bulb() //this is the default constructor with no argument.
   {
    System.out.println("Bulb is created");
   }  
   
 public static void main(String args[])
 {  
  Bulb b=new Bulb();  
  System.out.println("watt :"+ b.watt);
  System.out.println("color :"+ b.color);
  System.out.println("price :"+ b.price);
  }  
}

Note

If there is no constructor in a class, compiler will provide a default constructor.



Parameterized constructor

• A constructor with parameters (arguments) is called Parameterized constructor. • The purpose of parameterized constructor is to provide value to the instance variables as per object specification


class Bulb
{  
 int watt;  
 String color;
 float price;  
  
 Bulb(int w, float p, String clr)
 {   
  watt=w;  
  price=p;
  color=clr; 
  System.out.println("Bulb with specific value");
 }  
} 
 class Test156
 {  
 public static void main(String args[]) 
  {  
  Bulb b1=new Bulb(100,15.50f,"white");  
  Bulb b2=new Bulb(200,25.75f,"blue");  
  }  
}  
Footer with Map

Top