DEV Community

Ajay Raja
Ajay Raja

Posted on

Constructors__java:

constructor:

  • constructors play an important role in object creation.
  • Its main job is to initialize the object.
  • This process happens automatically when we use the "new" keyword to create an object.

Characteristics of Constructors:

  • Same name as the class
  • No return type
  • Used to Set Initial Values for Object Attributes

Why Do We Need Constructors in Java:

  • It ensures that an object is properly initialized before use

Types of Constructors in Java:

There are three types of constructor in java.

1)Default Constructor
2)No Argument constructor
3)Parameterized constructor
Enter fullscreen mode Exit fullscreen mode

1)Default Constructor:

  • if you do not create any constructor in the class.
  • Java provides a default constructor that initializes the object.

Example:
Default Constructor (A Class Without Any Constructor)

public class Main {
  int num1;
  int num2;

  public static void main(String[] args) {


    Main obj = new Main();


    System.out.println("num1 : " + obj.num1);
    System.out.println("num2 : " + obj.num2);
  }
}
Output

num1 : 0
num2 : 0

Enter fullscreen mode Exit fullscreen mode

2)No-Args (No Argument) Constructor:

  • constructor that does not accept any parameters.
  • It is used to initialize an object with default values

Key characteristics of a no-argument constructor:

  • No parameters: Its method signature does not include any arguments within the parentheses.
  • Same name as the class: Like all constructors, its name must exactly match the name of the class it belongs to.
  • No return type: Constructors, including no-argument constructors, do not have a return type, not even void.

3)Parameterized Constructor:

  • A constructor with one or more arguments is called a parameterized constructor.
  • you will need a constructor that accepts one or more parameters.
  • Just declare them inside the parentheses after the constructor's name.
public class Main {
  int num1;
  int num2;

  // Creating parameterized constructor 
  Main(int a, int b) {
    num1 = a;
    num2 = b;
  }

  public static void main(String[] args) {

    Main obj = new Main(10, 20);
    Main obj = new Main(100, 200);

    // Printing the objects values
    System.out.println("obj");
    System.out.println("num1 : " + obj.num1);
    System.out.println("num2 : " + obj.num2);

    System.out.println("obj");
    System.out.println("num1 : " + obj.num1);
    System.out.println("num2 : " + obj.num2);
  }
}

Enter fullscreen mode Exit fullscreen mode

Arguments:

  • arguments are the actual values that are passed to a method when it is called.
  • The specific data (values) that you pass into the method when you invoke it.

Top comments (0)