Tutorials Hut

Java - Constructors

Constructors

As we briefly touched constructors in previous article “Java Objects and Classes” and now we know that every java class has a constructor. Constructors are used to create a new object and initialize variables with some values.

If a developer or programmer does not create own constructor then the compiler creates one for it which is not visible in class but used to create class objects and this type of constructor is called default constructor.

A class in java can have one or more than one constructors.

Constructor can be created with arguments or without arguments, also they can be created with different access modifiers (public, private etc.)

Basic Syntax of Java Constructors:

  • A constructor with argument (Parameterized Constructors):
    <Access modifier/ if not provided default will be taken > <class name> (argument 1, argument 2 ..) { }
  • A constructor without argument (No Argument Constructors):
    <Access modifier/ if not provided default will be taken ><class name> () {}

Example of Java Constructors:

class Account{

int accountNumber;

//Below is our constructor

Account(int accNum){

accountNumber = accNum

}

}

In the above example we can see Account(int accNum){} is our constructor for Account class.

Constructors Types Based on Arguments.

There are two types of constructors:

  1. Parameterized constructor.
  2. No argument constructor.

Parameterized Constructors

A constructor which takes an argument or parameter is called a parameterized constructor.

Example:

/*

Class showing how to create parameterized constructor

 */

class Garden{

int numberOfFlowers;

//Below is our parametrised constructor

Garden(int noOfFlowers){

     numberOfFlowers = noOfFlowers;

 System.out.println("Hello, I am a parameterized constructor");

}

public static void main(String args[]) {

    Garden garden = new Garden(10);

}

}

In above we can see the Garden class has Garden(int noOfFlowers){}  constructor which takes parameter noOfFlowers.

No Argument Constructors

A constructor which takes no argument or parameter is called no argument constructor.

Example:

/*

Class showing how to create no argument constructor

 */

class Garden{




int numberOfFlowers;


//Below is our parametrised constructor

Garden(){




 System.out.println("Hello, I am a no argument constructor");




}


public static void main(String args[]) {

     Garden garden = new Garden();

}


}

In above we can see the Garden class has a Garden(){}  constructor with no arguments.

This is all guys by now you might have good idea about constructors and so you can move to our next chapter:














  • Leave a Reply

    Your email address will not be published. Required fields are marked *