Constructors in Java with example

Constructors in Java:

It would be simpler and more concise to initialize an object when it is first created, Java supports a special type of method that enables an object to initialize itself when it is created that is called Constructor.


Constructors in Java

Rule of Constructors in Java:

1. The constructor has the same name as the class itself.
2. A constructor doesn’t specify a return type, not even void.
3. In Java, a constructor can’t be abstract, final and static.

Example:

class square
{
 int length, width;
square(int x, int y)  // creating constructor
{
 length=x;
 width=y;
}
int area()
{
 return(length*width);
}
}

Types of Constructors in Java:

1. Default Constructor
2. Parameterized Constructor

Default Constructor:

When a constructor doesn’t have any parameter, then it is called Default Constructor.

Example:

class Car
{  
 Car()  // Default Constructor
{
 System.out.println("Car is moving");
}  
public static void main(String args[])
{  
 Car c1=new Car();  // Calling Default Constructor
}  
}

Output:

Car is moving

Parameterized Constructor:

A constructor which has a specific number of parameters that is called parameterized constructor.
Example :

class Integer
{
 int n;
Integer(int e)  // Parameterized Constructor
{n=e;}
void Palindrome()
{
 int rem, q, rev=0;
 q=n;
while(n!=0)
{
 rem=n%10;
 rev=(rev*10)+rem;
 n=n/10;
 }
if(q==rev)
{
 System.out.println("It is a Palindrome Number");
}
else
{
  System.out.println("It is Not a Palindrome Number");
}
}
}
public class Test
{
 public static void main(String args[])
{
  Integer i1=new Integer(121);
  i1.Palindrome();
}
}

Output:

It is a Palindrome Number