What is a Java constructor?

Constructor is a powerful component programming. Use them to release the full potential of Java.

In open source, cross-platform programming field, Java is no doubt (?) Is the undisputed heavyweight language. Although there are many great cross-platform framework , but few are as Java as a unified and direct.

Of course, Java is a very complex language, with its own subtleties and practices. Java withConstructor constructorOne of the most frequently asked questions about is: what they are, what their role is?

In short: create a new constructor in JavaObjectsobjectAction to take when. When the Java application creates an instance of the class you write, it checks the constructor. If the (class) constructor exists, it will create an instance of Java when running code in the constructor. These words contained in a large number of technical terms, but when you see it in practice will be more clearly, so make sure you have installed Java and ready for presentation.

Do not use constructor routine development

If you're writing Java code, then you are already using the constructor, even if you may not know it. All classes in Java have a constructor, because even if you do not create a constructor, Java will be generated for you when you compile a code. However, in order to demonstrate, ignore the hidden constructor provided by Java (because the default constructor does not add any extra functionality), and observed no explicit constructor circumstances.

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

First, you can create a class to represent a dice dice. You play for a long time , "Dungeons and Dragons" , so you decide to create a 20-sided dice are. In this example code, the variable diceis an integer of 20, representing the maximum possible number of dice (dice rolled number of a dice edge 20 should not exceed 20) throw. Variable rollis the ultimate random number placeholder randused as a random number seed.

import java.util.Random;

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

Next, DiceRollercreate a class function to perform the step of rolling the mold computer simulation must be taken: from randobtaining an integer and assigned to the rollvariable, taking into account counting from zero but Java die surface 20 is not the value 0 case, rollplus 1, and then print the results.

import java.util.Random;

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

Finally, it produces DiceRollerinstance of the 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 (such as the OpenJDK ), you can run your application on the terminal:

$ java dice.java
You rolled a 12
复制代码

In this embodiment, no explicit constructor. This is a very valid and legitimate Java applications, but it has little limitations. For example, if you put the game "Dungeons and Dragons" on the side, in the evening to play some "Yahtzee", you will need six-sided dice. In this simple example, change the code will not have too much trouble, but in a complex code, this is not a realistic option. One way to solve this problem is to use the constructor.

The role of the constructor

The sample project DiceRollerclass represents a virtual dice factory: When it is called, it creates a virtual dice, then "roll." However, by writing a custom builder, you can roll the dice to make an application you want to ask what type of dice simulation.

Most of the code is the same, except that the constructor accepts a numeric parameter indicating the number of faces. This figure 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;
  }
复制代码

Analog scrolling function remains the same:

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

Provide any arguments when running the application to provide a major part of the code. This would indeed be a complex application, you need to carefully parse the parameters and check unexpected results, but for this example, the only precaution is to convert a string to an integer parameter type.

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

Start the application, and provides a number of faces you want to have the dice:

$ 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, will be sidesvariable is set to any number specified by the user.

Constructor is a powerful component programming. Practice using them to unlock the full potential of Java.


via: opensource.com/article/19/…

Author: Seth Kenlon topics: lujun9972 Translator: laingke proofread: wxy

This article from the LCTT original compiler, Linux China is proud

Guess you like

Origin juejin.im/post/5daafbbaf265da5b707ea6fe