Subscribe Us

Constructor In Java

.
Constructor in java 
In java programming language , A constructor is a block of code used to initialize the object . when ever we create a object by new keywords after the new keyword that part is constructor .

Example of Constructor 

Class Bike
{  
Bike()    //This is constructor
{
System.out.println("Speed is 80 Kmph");
}  


Types of constructor in java 
There are two 3 types of constructor in java .
1) Default constructor. 
2) No-argument constructor .
3) Parameterized constructor .

Default Constructor 

inside a java class if you are not declare any constructor then the java compiler generate the default constructor with empty implementation inside the code .default constructor are not visible inside the code. default constructor inserted during the compilation and exists in .class file.



Example of Default Constructor 
class Bike
{  
Bike()    //This is default constructor
{
System.out.println("Speed is 80 Kmph");
}  
public static void main(String args[])
{
Bike b = new Bike();

}
 Output : Speed is 80kmph

no-argument Constructor 

In java , Constructor with zero (0) argument is known as the no argument constructor . in java programming if we are not declare any constructor then compiler generate default constructor with zero argument constructor and if we declare the no-argument constructor or parameterized constructor the compiler not generate default constructor .

Example of no-argument constructor 
class Bike
{  
Bike()    //This is no-argument constructor
{
System.out.println("Speed is 80 Kmph");
}  
public static void main(String args[])
{
Bike b = new Bike();

}

 Output : Speed is 80kmph

Parameterized Constructor 

Constructor with parameter is known as the parameterized constructor .

Example of parameterized constructor 



class Bike
{  
int speed;
String color;
Bike(int fspeed ,String bcolor )//This is parameterized constructor
{
this.speed= fspeed;
this.color= bcolor;
void Test(){
System.out.println("Speed :"+speed+"Color :"+color);
public static void main(String args[])
{
Bike b = new Bike(120, "RED");
Bike b1 = new Bike(130, "Green");
}
Output: Speed :120 Color :RED
            Speed :130 Color :Green

Constructor In Java






Post a Comment

0 Comments