Constructors


A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. Note that the constructor name must match the class name, and it cannot have a return type (like void). All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.

// Create a MyClass class.
public class MyClass {
  // Create a class attribute.
  int x;

  public static void main( String[ ] args ) {
    // Create an object of class MyClass (this will call the constructor).
    MyClass myObj = new MyClass( );
    // Print the value of x.
    System.out.println( myObj.x );     // Output: 5
  }

  // Create a class constructor for the MyClass class.
  public MyClass( ) {
    x = 5;  // Set the initial value for the class attribute x.
  }
}

Constructor Parameters
Constructors can also take parameters, which are used to initialize attributes. The following example adds an int y parameter to the constructor. Inside the constructor, we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:

public class MyClass {
  int x;

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

  public MyClass( int y ) { x = y; }
}




      “Failure is the condiment that gives success its flavor.”    
      ― Truman Capote