DEV Community

Bharath kumar
Bharath kumar

Posted on

Constructor in java

What is Constructor ?
A constructor is a special type of method used in object-oriented programming languages to initialize objects.
The constructor is called automatically every time when an object is created.

A constructor is used to allocate memory and initialize the state of a new object.
Constructors have the same name as the class and do not have a return type, not even void.

Characteristics of Constructors:
this keyword is used a constructor code block in the java programming. Example: this.name= name; assign the values automatically call when the object is created and passes through the values into parameters...

1. Same Name as the Class: A constructor has the same name as the class in which it is defined.
2.No Return Type: Constructors do not have any return type, not even void. The main purpose of a constructor is to initialize the object, not to return a value.
3.Automatically Called on Object Creation: When an object of a class is created, the constructor is called automatically to initialize the object’s attributes.
4.Used to Set Initial Values for Object Attributes: Constructors are primarily used to set the initial state or values of an object’s attributes when it is created.

Syntax:

public class MyClass {
    // Constructor
    public MyClass() {

    }

    // Other methods and variables can be defined here
}

Enter fullscreen mode Exit fullscreen mode

Example :

class Geeks {

    // data members of the class
    String name;
    int id;

    Geeks(String name, int id) {
        this.name = name;
        this.id = id;
    }
}

class GFG 
{
    public static void main(String[] args)
    {

        Geeks geek1 = new Geeks("Sweta", 68);
        System.out.println("GeekName: " + geek1.name
                           + " and GeekId: " + geek1.id);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output :

GeekName: Sweta and GeekId: 68

Enter fullscreen mode Exit fullscreen mode

Reference:https://www.geeksforgeeks.org/java/constructors-in-java/

Top comments (0)