Java

How do Constructors Work in Java

In this article we will look at constructors in Java.

A constructor in Java is a special method that is used to initialize an object when it is created. It has the same name as the class and does not have a return type. The main use of a constructor is to set the initial state of an object.




There are two main characteristics of a constructor in Java:

  1. It has the same name as the class.
  2. It does not have a return type, not even void.

There are two types of constructors in Java:

  1. Default constructor: This constructor is provided by the compiler if no constructors are defined by the programmer.
  2. Parameterized constructor: This constructor is defined by the programmer and takes one or more parameters.

Constructors play an important role in object-oriented programming as they are used to create and initialize objects. They are also used to set the initial state of an object.

The syntax for creating a constructor in Java is as follows:

Use of Constructors:

constructors

The class TicTacToe represents the overall game of Tic-Tac-Toe. It contains a field for each of the 9 squares on the game board, named block1, block2, …, block9. The class also has a method named “display()” which is used to display the game board to the user.

In the display() method, block1 is created as a new Square object and the createBlock() method is called on it. This creates and initializes the first square on the game board. The same process is then repeated for the remaining 8 squares, block2, block3, …, block9.

The code to arrange the squares as a 3×3 matrix is not shown in the example, but it would likely involve positioning the squares on the screen in the correct positions relative to each other to form the 3×3 grid.

It’s worth noting that the example is not complete and doesn’t show how the class TicTacToe is supposed to be used. It doesn’t show how the blocks get their values, and the game logic is missing. Also, the example is not using constructors, instead it creates the blocks using the new operator, and then calling createBlock() method.

It would be better to use constructors to initialize the blocks, and also it would be more efficient to create all the blocks in a loop rather than having to write the same code for each block individually.

The Square class will be something as shown below:

The class “Square” represents an individual square on the Tic-Tac-Toe game board. It contains a single field “side” which represents the length of one side of the square. It also has a method named “createBlock()” which is used to create the square and initialize its side length.

In the createBlock() method, the side field is assigned a value of 4, which sets the length of one side of the square to 4 units. The method then includes additional code to create the square itself, which is not shown in the example. This code would likely involve drawing the square on a screen or creating a square object in memory.

It’s worth noting that the example is not complete and doesn’t show how the class Square is supposed to be used. It doesn’t show how the side of the square is supposed to be set, and it also doesn’t show how the square is supposed to be displayed.

It would be better to use a constructor to initialize the side of the square and also it would be more efficient to create the square on the constructor rather than having to call createBlock() method.

The driver program (which executes our logic classes) will be as shown below:

If you look at the above program, the task of display() method is to create 9 square blocks by internally calling createBlock() method of Square class. This whole process can be seen as initializing the board. Every time, when someone wants to play the game, the board has to be initialized (square blocks have to be created and displayed to the user). To make the initialization process simple, constructors have been introduced whose sole purpose is to initialize the object. Now, let’s modify our previous classes to include constructors. The code is shown below:

The Square class will be as shown below:

The driver program (which executes our logic classes) will be as shown below:

The class “Game” contains a main method, which is the entry point of a Java program. In the main method, an object of the TicTacToe class is created using the “new” operator and stored in a variable named “board”. The display() method is then called on the board object, which causes the game board to be displayed to the user.

The code inside the main method creates an instance of the TicTacToe class and calls its display method. The display method should be calling the createBlock() method on each block (Square class) to create the game board.

The “//Other code” comment implies that there is additional code that is not shown in the example, which would likely involve the game logic and handling user input.

It’s worth noting that the example is incomplete and doesn’t show how the game is supposed to be played, it only shows how the game board is supposed to be displayed.

Constructor Invocation:

Constructor invocation refers to the process of calling a constructor to create and initialize an object of a class. In Java, constructors are invoked using the “new” operator, followed by the class name and parentheses containing any required arguments for the constructor.

For example, to create an object of the class “MyClass” and call its default constructor (a constructor that takes no arguments), you would use the following code:

To create an object of the class “MyClass” and call a constructor that takes an int and a String as arguments, you would use the following code:

When a constructor is invoked, it initializes the fields of the new object and sets its initial state. The constructor is also responsible for any additional operations required to create a fully formed object, such as allocating memory or initializing other objects.

It’s worth noting that constructors can also be invoked using the class’s newInstance() method, and reflection, but they are less commonly used in practice.

Types of Constructor:

There are two main types of constructors in Java:

  1. Default constructor: This constructor is provided by the compiler if no constructors are defined by the programmer. It has no parameters and it is used to provide the default values to the object like 0, null, etc.
  2. Parameterized constructor: This constructor is defined by the programmer and takes one or more parameters. These parameters are used to initialize the fields of the object when it is created. It can be used to initialize the state of an object with specific values at the time of object creation.
  3. Copy constructor: This constructor is used to create a new object as a copy of an existing object. It takes an object of the same class as a parameter and creates a new object with the same field values as the original object.
  4. Private constructor: This constructor is defined with private access modifier. It can only be accessed within the same class, which means the other classes cannot instantiate the class. It is mostly used in Singleton design pattern.
  5. Static constructor: This constructor is not a real constructor but a block of code that is executed when the class is loaded. It is used to initialize static fields and perform other static initialization tasks.

Java also supports other types of constructor, like chained constructor, but they are less common.

Parameter less constructor: The class “Square” has a constructor with no parameters, and it initializes the “side” field with a value of 4.

A parameterless constructor is useful when you want to provide a default initialization for an object of a class. In this example, every time an object of the class “Square” is created, its “side” field will be set to 4, which is the default value.

It’s worth noting that if a class does not have any constructor defined, the Java compiler automatically provides a default constructor with no parameters and no implementation, but if a class has at least one constructor defined by the programmer, then the compiler does not provide a default constructor.

It’s also worth noting that, in the example, the constructor does not have any access modifier, by default the constructor is package-private and can only be accessed within the same package.

In the above example, Sqaure() is a zero parameter or parameter less constructor which initializes the side of a square to 4.

Parameterized constructor:The class “Square” has a constructor that takes an int parameter named “s”, and it initializes the “side” field with the value passed in through the parameter.

A parameterized constructor is useful when you want to provide a way to initialize an object of a class with specific values when it is created. In this example, when an object of the class “Square” is created and the constructor is called with an argument, it initializes the “side” field with the value passed as an argument.

For example, if you want to create a square with a side of 6 units, you can use the following code:

This will create a new Square object, and call the constructor with the parameter 6, initializing the side field to 6.

It’s also worth noting that, in the example, the constructor does not have any access modifier, by default the constructor is package-private and can only be accessed within the same package.

Copy constructor: The class “Square” has a constructor that takes an object of the same class as a parameter, named “original”. It initializes the “side” field with the value of the “side” field of the original object.

A copy constructor is used to create a new object with the same field values as the original object. This can be useful when you want to create a copy of an object without modifying the original object.

For example, if you have an existing Square object named “originalSquare” and you want to create a new object “mySquare” with the same values, you can use the following code:

This will create a new Square object, and call the copy constructor, passing the originalSquare as parameter. The copy constructor will copy the value of the side field from the originalSquare and initialize the new object’s side field with that value.

It’s worth noting that the class “Square” in the example provided, has a default constructor that assigns the value 4 to the side field, but it’s not a good practice to have both a default constructor and a copy constructor. In general, if a class has a copy constructor, it shouldn’t have a default constructor.

Now let’s an example which covers all three types of constructors:

The output of the above driver program will be:

In the driver program, three objects of the Square class are created using the different constructors provided in the Square class.

The first object “normal” is created using the parameterless constructor, which assigns the value of 4 to the “side” field.

The second object “original” is created using the single parameter constructor, which assigns the value of 8 to the “side” field.

The third object “duplicate” is created using the copy constructor, which assigns the value of “original.side” to the “side” field. Since “original” object’s side field is 8, that’s the value that is assigned to the duplicate’s side field.

Finally, the program prints out the values of the “side” field for each of the three objects.

It’s worth noting that in the driver program, the class name is “Square” but in the main method is written as “Sqaure”, there is a typo in the class name.

Take your time to comment on this article.

Leave a Comment