What is a Java constructor?

Constructors are powerful components of programming. Use them to unlock the full potential of Java.
--Seth Kenlon (author)

In the field of open source and cross platform programming, Java is undoubtedly an indisputable heavyweight language. Although there are many great cross platform frameworks, few are like   Java   So unified and direct.

Of course, Java is also a very complex language with its own subtleties and conventions. Java and   One of the most common questions about constructors is: what are they and what are their roles?

In short: constructors create new objects in Java   The operation to be performed when an object is. When a Java application creates an instance of a class you write, it checks the constructor. If a constructor exists, Java will run the code in the constructor when the instance is created. These sentences contain a lot of technical terms, but it will be clearer when you see its practical application, so please make sure you have installed Java   And ready to demonstrate.

Daily development without constructors

If you are writing java code, you are already using a constructor, even if you may not know it. All classes in java have a constructor, because even if you don't create a constructor, Java will generate one for you when compiling code. However, for demonstration purposes, ignore the hidden constructor provided by Java (because the default constructor does not add any additional functionality) and observe that there is no explicit constructor.

Suppose you are writing a simple Java dice application because you want to generate a pseudo-random number for the game.

First, you can create a dice class to represent a dice. You played dungeons and dragons for a long time, so you decided to create a 20 sided dice. In this sample code, variables   dice   Is an integer of 20, indicating the maximum number of rolls possible (the number of rolls of a 20 sided die cannot exceed 20). variable   roll   Is a placeholder for the final random number, rand   Used as a random number seed.

//java learning and exchange: 737251827 enter to receive learning resources and ask questions about leaders with ten years of development experience for free!
import java.util.Random;

public class DiceRoller {
  private int dice = 20;
  private int roll;
  private Random rand = new Random();

Next, in   DiceRoller   Class to perform the steps that must be taken by computer simulation module scrolling: from   rand   Gets an integer from and assigns it to   Roll variable. Considering that Java starts counting from 0 but the dice on 20 sides have no 0 value, roll   Add 1 and print the result.

import java.util.Random;

public class DiceRoller {
  private int dice = 20;
  private int roll;
  private Random rand = new Random();

Finally, produce   DiceRoller   Class and call its key functions   Roller:

// main loop
public static void main (String[] args) {
  System.out.printf("You rolled a ");

  DiceRoller App = new DiceRoller();
  App.Roller();
  }
}

As long as you install the Java development environment (e.g   OpenJDK), you can run your application on the terminal:

$ java dice.java 
You rolled a 12

In this case, there is no explicit constructor. This is a very effective and legitimate Java application, but it has a few limitations. For example, if you put the game "dragon and dungeon" aside and play some "speedboat dice" at night, you will need six sided dice. In this simple example, changing the code won't be too much trouble, but it's not a realistic choice in complex code. One way to solve this problem is to use constructors.

Function of constructor

In this sample project   DiceRoller   Class represents a virtual die factory: when it is called, it creates a virtual die and then "rolls". However, by writing a custom constructor, you can have the dice application ask which type of dice you want to simulate.

Most of the code is the same, except that the constructor accepts a numeric parameter representing the number of faces. This number does not exist yet, but it will be created later.

import java.util.Random;

public class DiceRoller {
  private int dice;
  private int roll;
  private Random rand = new Random();

  // constructor
  public DiceRoller(int sides) {
    dice = sides;
  }

The function that simulates scrolling remains unchanged:

public void Roller() {
  roll = rand.nextInt(dice);
  roll += 1;
  System.out.println (roll);
}

The main part of the code provides any parameters provided when running the application. This will be a complex application. You need to carefully parse the parameters and check for unexpected results, but for this example, the only precaution is to convert the parameter string to integer type.

public static void main (String[] args) {
  System.out.printf("You rolled a ");
  DiceRoller App = new DiceRoller( Integer.parseInt(args[0]) );
  App.Roller();
}

Start this application and provide the number of faces you want the dice to have:

$ java dice.java 20
You rolled a 10

$ java dice.java 6
You rolled a 2

$ java dice.java 100
You rolled a 44

The constructor has accepted your input, so when you create a class instance, it will   sides   The variable is set to any number specified by the user.

Constructors are powerful components of programming. Practice using them to unlock the full potential of Java.

Tags: Java Back-end Programmer

Posted on Sat, 20 Nov 2021 18:16:12 -0500 by the-Jerry