Java - Class Constructor Definition

What is Constructor?

A constructor can create and initialize an object of a class.

Syntax

The constructor looks similar to a method.

The general syntax for a constructor declaration is

<Modifiers> ClassName(<parameters list>) throws <Exceptions list> {
   // Body of constructor
}

A constructor can have its access modifier as public, private, protected, or package-level (no modifier).

The constructor name is the same as the simple name of the class.

A constructor may have parameters.

Example

The following code shows an example of declaring a constructor for a class Test.

public class Test {
   public Test() {
         // Code goes here
   }
}

A constructor does not have a return type.

Just the name itself does not make a method or constructor.

If the name of a construct is the same as the simple name of the class, it could be a method or a constructor.

If it has a return type, then it is a method.

If it does not have a return type, it is a constructor.

You cannot even specify void as a return type for a constructor.

public class Test {
  // Below is a method, not a constructor.
  public void Test() {
     // Code goes here
  }
}

The following code uses a constructor of the Test class to initialize an object of the Test class:

Test t = new Test();

Related Topics

Quiz