logo

Java Constructors


Show

A constructor initializes an item while it is generated. It has a similar name as its division and is syntactically alike to a technique. However, constructors have no open return type.

Usually, you will employ a constructor to offer initial values to the occurrence variables described by the class, or to do any other start-up process required to generate a fully shaped object.

Entire classes have constructors, whether you name one or not since Java mechanically supplies a default constructor that initializes every member variable to zero. But, once you classify your own constructor, the default constructor is no longer employed.

class ClassName {
   ClassName() {
   }
}

Java allows two types of constructors namely:

  • No argument Constructors
  • Parameterized Constructors

No argument Constructors

As the name specifies there is no disagreement constructors of Java accepted any parameters. Instead, by means of these constructors, the case variables of a system will be initialized with fastened values for entire objects.

Example

Public class MyClass {
   Int num;
   MyClass() {
      num = 100;
   }
}

You would call the constructor to initialize objects as follows

public class ConsDemo {
   public static void main(String args[]) {
      MyClass t1 = new MyClass();
      MyClass t2 = new MyClass();
      System.out.println(t1.num + " " + t2.num);
   }
}

This would produce the following result

100 100

Parameterized Constructors

Mainly frequently, you will call for a constructor that recognizes one or more parameters. Parameters are adjoined to a constructor in the identical way that they are inserted into a method; just announce them within the parentheses after the constructor's forename.

Example

Here is a simple example that uses a constructor:

// A simple constructor.
class MyClass {
   int x;
   
   // Following is the constructor
   MyClass(int i ) {
      x = i;
   }
}

You would call the constructor to initialize objects as follows:

public class ConsDemo {
   public static void main(String args[]) {
      MyClass t1 = new MyClass( 10 );
      MyClass t2 = new MyClass( 20 );
      System.out.println(t1.x + " " + t2.x);
   }
}

This would produce the following result:

10 20