DEV Community

Mohan Mogi
Mohan Mogi

Posted on

Java Constructor Programming Examples for Beginners

What is Constructor?

1.Constructorin java is special method that is used to initailze objects.
2.It is automatically called when an object of a class is created.
3.It is used to set initial values for object attributes.

Rules of Constructor:

◆ Constructor name must be the same as the class name.
◆ Constructor has no return type (not even void).
◆ Constructor is called automatically when using the new keyword.
◆ Constructors can be overloaded.

Types of Constructors:

  1. Default Constructor
  2. No-Argument Constructor
  3. Parameterized Constructor

Important Keywords:

◆ new → Creates an object and calls the constructor.
◆ this() → Calls another constructor in the same class.
◆ super() → Calls the parent class constructor.

Create a constructor:

Explanation:
*Creates a class named Main.
public class Main {

*Declares an instance variable x.
int x;

*Declares an instance variable x.
public Main() {
x = 5;
}

◆ This is the constructor.
◆ It has the same name as the class (Main).
◆ It has no return type.
◆ It runs automatically when an object is created.
◆ It initializes x to 5.

Main myObj = new Main();

◆ Creates a new object.
◆ Automatically calls the constructor.
◆ The constructor sets x = 5.

System.out.println(myObj.x);
◆ Prints the value of x.

output: 5

Top comments (0)