Start Coding Now

Constructors in Java - Types & Examples

Learn about constructors in Java. Default constructor, parameterized constructor, and copy constructor explained.

What is a Constructor?

A constructor is a special method used to initialize objects. It is called when an object of a class is created.

Rules:

  • Method name must match Class name.
  • Must have no return type (not even void).
  • Can accept parameters.
  • public class MyClass {
        int x;

    // Constructor public MyClass() { x = 5; }

    public static void main(String[] args) { MyClass myObj = new MyClass(); // Constructor called System.out.println(myObj.x); // Outputs 5 } }

    Frequently Asked Questions