Constructor

A constructor is a special method that is called when a new object of a particular class is created using the “new” operator.

The constructor is called like this:

Cell cell1 = new Cell(CellDefinition cd, Model model)

• Cell cell1 - indicates that an object cell1 belonging to the Cell class is being created.
• new Cell - creation of a new object.
• CellDefinition cd - the argument (cd) and its type/class (CellDefinition) passed to the constructor.

Basic rules for declaring a constructor in java:

  • The constructor name must match the class name.

  • The constructor does not have a return type.

Inside the class, the constructor is declared as follows:

// Cell class
public class Cell {

   // Class fields:
   // cd - an object of CellDefinition class
   // model - an object of Model class
   private CellDefinition cd;
   private Model model;

   // Constructor that takes two parameters
   public Cell(CellDefinition cd, Model model) {

      // Assign the parameters received by the constructor to the class fields
      this.cd = cd;
      this.model = model;
   }

}