Java Constructors


Java Constructors

Constructor in Java is a special method used to get things started. A constructor is called when a class object is built. Can be used to set initial values ​​for object attributes:


Example

Create a constructor:

// Create a Main class
            public class Main {
              int x;  // Create a class attribute
            
              // Create a class constructor for the Main class
              public Main() {
                x = 5;  // Set the initial value for the class attribute x
              }
            
              public static void main(String[] args) {
                Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
                System.out.println(myObj.x); // Print the value of x
              }
            }
            
            // Outputs 5
            

Note that the constructor name must match the class name, and may not have a return type (such as void).

Also note that the constructor is named when the object is created.

All classes have builders by default: if you do not generate a class constructor yourself, Java creates one for you. However, you cannot set the initial values ​​of the object attribute.


Constructor Parameters

constructor can also take parameters, which are used to launch attributes.

The following example adds an int y parameter to a constructor. Inside the constructor we place x to y (x = y). When we call a constructor, we pass the parameter to the constructor (5), which will set the value of x to 5:


Example
public class Main {
            int x;
          
            public Main(int y) {
              x = y;
            }
          
            public static void main(String[] args) {
              Main myObj = new Main(5);
              System.out.println(myObj.x);
            }
          }
          
          // Outputs 5
          

You can have as many parameters as you want:


Example
public class Main {
            int modelYear;
            String modelName;
          
            public Main(int year, String name) {
              modelYear = year;
              modelName = name;
            }
          
            public static void main(String[] args) {
              Main myCar = new Main(1969, "Mustang");
              System.out.println(myCar.modelYear + " " + myCar.modelName);
            }
          }
          
          // Outputs 1969 Mustang