Constructors  in Java

Constructors in Java

·

2 min read

Today, we'll be learning about constructors in java. It is one of the essential topics of Object Oriented programming. Constructor helps in reducing the complexity of programs, by setting the properties(value) of an object at the time of Object creation. It is just like when you buy a car, it must have some default properties like color, fuel tanks, or gears. So we use a constructor, to set some default properties to our object at the time of creation.

What is constructor

Constructor is a method of a class, which is called automatically, whenever you create an object. The default constructor is provided by the compiler.

Rules of creating a constructor in java

  • The constructor doesn't have any return type.

  • The constructor must have the same name as that of a class.

  • The constructor cannot be abstract, static, final, or synchronized.

Types of constructors

There are two types of constructors in java -

  • Parameterized constructor

  • Non-parameterized constructor

Parameterized constructor:

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

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to the distinct objects. However, you can provide the same values also.

public class Rectangle{
    private int length, private int breadth;
    // double paramertized constructor
   public Rectangle(int l,int b){
        length = l;
        breadth = b;
        }
    //single arg parameterized constructor
    public Rectangle(int s){
    length = breadth =s;
}
    public static void main(String args[]){
       //here two params constructor is called 
       Rectangle rect = new Rectangle(5,10);
        //here single param constructor is called
       Rectangle rec = new Rectangle(4);


    }

}

Non-Parameterized Constructors

Constructors with no parameter is called a non - parameterized constructor can also be refer as default constructor.

public class Rectangle{
    private int length;
    private int breadth;
    //non-parameterized constructor
    public Rectangle(){
        length = 1;
        breadth =1;
        }
    public static void main(String args[]){
        //constructor calling
        Rectangle r = new Rectangle();
        //here length and breadth will be 1 set by the constructor
        }

    }