mirror of
https://github.com/LCTT/TranslateProject.git
synced 2025-02-03 23:40:14 +08:00
20190614-what-java-constructor translated
This commit is contained in:
parent
567b0c2d1b
commit
cb52871f62
@ -1,158 +0,0 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: (laingke)
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: subject: (What is a Java constructor?)
|
||||
[#]: via: (https://opensource.com/article/19/6/what-java-constructor)
|
||||
[#]: author: (Seth Kenlon https://opensource.com/users/seth/users/ashleykoree)
|
||||
|
||||
What is a Java constructor?
|
||||
======
|
||||
Constructors are powerful components of programming. Use them to unlock
|
||||
the full potential of Java.
|
||||
![][1]
|
||||
|
||||
Java is (disputably) the undisputed heavyweight in open source, cross-platform programming. While there are many [great][2] [cross-platform][2] [frameworks][3], few are as unified and direct as [Java][4].
|
||||
|
||||
Of course, Java is also a pretty complex language with subtleties and conventions all its own. One of the most common questions about Java relates to **constructors** : What are they and what are they used for?
|
||||
|
||||
Put succinctly: a constructor is an action performed upon the creation of a new **object** in Java. When your Java application creates an instance of a class you have written, it checks for a constructor. If a constructor exists, Java runs the code in the constructor while creating the instance. That's a lot of technical terms crammed into a few sentences, but it becomes clearer when you see it in action, so make sure you have [Java installed][5] and get ready for a demo.
|
||||
|
||||
### Life without constructors
|
||||
|
||||
If you're writing Java code, you're already using constructors, even though you may not know it. All classes in Java have a constructor because even if you haven't created one, Java does it for you when the code is compiled. For the sake of demonstration, though, ignore the hidden constructor that Java provides (because a default constructor adds no extra features), and take a look at life without an explicit constructor.
|
||||
|
||||
Suppose you're writing a simple Java dice-roller application because you want to produce a pseudo-random number for a game.
|
||||
|
||||
First, you might create your dice class to represent a physical die. Knowing that you play a lot of [Dungeons and Dragons][6], you decide to create a 20-sided die. In this sample code, the variable **dice** is the integer 20, representing the maximum possible die roll (a 20-sided die cannot roll more than 20). The variable **roll** is a placeholder for what will eventually be a random number, and **rand** serves as the random seed.
|
||||
|
||||
|
||||
```
|
||||
import java.util.Random;
|
||||
|
||||
public class DiceRoller {
|
||||
private int dice = 20;
|
||||
private int roll;
|
||||
private [Random][7] rand = new [Random][7]();
|
||||
```
|
||||
|
||||
Next, create a function in the **DiceRoller** class to execute the steps the computer must take to emulate a die roll: Take an integer from **rand** and assign it to the **roll** variable, add 1 to account for the fact that Java starts counting at 0 but a 20-sided die has no 0 value, then print the results.
|
||||
|
||||
|
||||
```
|
||||
public void Roller() {
|
||||
roll = rand.nextInt(dice);
|
||||
roll += 1;
|
||||
[System][8].out.println (roll);
|
||||
}
|
||||
```
|
||||
|
||||
Finally, spawn an instance of the **DiceRoller** class and invoke its primary function, **Roller** :
|
||||
|
||||
|
||||
```
|
||||
// main loop
|
||||
public static void main ([String][9][] args) {
|
||||
[System][8].out.printf("You rolled a ");
|
||||
|
||||
DiceRoller App = new DiceRoller();
|
||||
App.Roller();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
As long as you have a Java development environment installed (such as [OpenJDK][10]), you can run your application from a terminal:
|
||||
|
||||
|
||||
```
|
||||
$ java dice.java
|
||||
You rolled a 12
|
||||
```
|
||||
|
||||
In this example, there is no explicit constructor. It's a perfectly valid and legal Java application, but it's a little limited. For instance, if you set your game of Dungeons and Dragons aside for the evening to play some Yahtzee, you would need 6-sided dice. In this simple example, it wouldn't be that much trouble to change the code, but that's not a realistic option in complex code. One way you could solve this problem is with a constructor.
|
||||
|
||||
### Constructors in action
|
||||
|
||||
The **DiceRoller** class in this example project represents a virtual dice factory: When it's called, it creates a virtual die that is then "rolled." However, by writing a custom constructor, you can make your Dice Roller application ask what kind of die you'd like to emulate.
|
||||
|
||||
Most of the code is the same, with the exception of a constructor accepting some number of sides. This number doesn't exist yet, but it will be created later.
|
||||
|
||||
|
||||
```
|
||||
import java.util.Random;
|
||||
|
||||
public class DiceRoller {
|
||||
private int dice;
|
||||
private int roll;
|
||||
private [Random][7] rand = new [Random][7]();
|
||||
|
||||
// constructor
|
||||
public DiceRoller(int sides) {
|
||||
dice = sides;
|
||||
}
|
||||
```
|
||||
|
||||
The function emulating a roll remains unchanged:
|
||||
|
||||
|
||||
```
|
||||
public void Roller() {
|
||||
roll = rand.nextInt(dice);
|
||||
roll += 1;
|
||||
[System][8].out.println (roll);
|
||||
}
|
||||
```
|
||||
|
||||
The main block of code feeds whatever arguments you provide when running the application. Were this a complex application, you would parse the arguments carefully and check for unexpected results, but for this sample, the only precaution taken is converting the argument string to an integer type:
|
||||
|
||||
|
||||
```
|
||||
public static void main ([String][9][] args) {
|
||||
[System][8].out.printf("You rolled a ");
|
||||
DiceRoller App = new DiceRoller( [Integer][11].parseInt(args[0]) );
|
||||
App.Roller();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Launch the application and provide the number of sides you want your die 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 the class instance is created, it is created with the **sides** variable set to whatever number the user dictates.
|
||||
|
||||
Constructors are powerful components of programming. Practice using them to unlock the full potential of Java.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/19/6/what-java-constructor
|
||||
|
||||
作者:[Seth Kenlon][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[laingke](https://github.com/laingke)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/seth/users/ashleykoree
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/build_structure_tech_program_code_construction.png?itok=nVsiLuag
|
||||
[2]: https://opensource.com/resources/python
|
||||
[3]: https://opensource.com/article/17/4/pyqt-versus-wxpython
|
||||
[4]: https://opensource.com/resources/java
|
||||
[5]: https://openjdk.java.net/install/index.html
|
||||
[6]: https://opensource.com/article/19/5/free-rpg-day
|
||||
[7]: http://www.google.com/search?hl=en&q=allinurl%3Adocs.oracle.com+javase+docs+api+random
|
||||
[8]: http://www.google.com/search?hl=en&q=allinurl%3Adocs.oracle.com+javase+docs+api+system
|
||||
[9]: http://www.google.com/search?hl=en&q=allinurl%3Adocs.oracle.com+javase+docs+api+string
|
||||
[10]: https://openjdk.java.net/
|
||||
[11]: http://www.google.com/search?hl=en&q=allinurl%3Adocs.oracle.com+javase+docs+api+integer
|
156
translated/tech/20190614 What is a Java constructor.md
Normal file
156
translated/tech/20190614 What is a Java constructor.md
Normal file
@ -0,0 +1,156 @@
|
||||
[#]: collector: (lujun9972)
|
||||
[#]: translator: (laingke)
|
||||
[#]: reviewer: ( )
|
||||
[#]: publisher: ( )
|
||||
[#]: url: ( )
|
||||
[#]: subject: (What is a Java constructor?)
|
||||
[#]: via: (https://opensource.com/article/19/6/what-java-constructor)
|
||||
[#]: author: (Seth Kenlon https://opensource.com/users/seth/users/ashleykoree)
|
||||
|
||||
Java 构造器是什么?
|
||||
======
|
||||
构造器是编程的强大组件。使用它们来释放 Java 的全部潜力。
|
||||
![][1]
|
||||
|
||||
在开源、跨平台编程领域,Java 无疑是无可争议的重量级语言。尽管有许多[伟大的][2][跨平台][2][框架][3],但很少有像 [Java][4] 那样统一和直接的。
|
||||
|
||||
当然,Java 还是一种非常复杂的语言,具有自己的微妙之处和约定。Java 中与**构造器**有关的最常见问题之一是:它们是什么,它们的作用是什么?
|
||||
|
||||
简而言之:构造器是在 Java 中创建新**对象**时执行的操作。当 Java 应用程序创建你编写的类的实例时,它将检查构造器。如果存在构造器,则 Java 在创建实例时将运行构造器中的代码。这几句话中包含了大量的技术术语,但是当你看到它的实际应用时就会更加清楚,所以请确保你已经[安装了 Java][5] 并准备好进行演示。
|
||||
|
||||
### 没有使用构造器的开发日常
|
||||
|
||||
如果你正在编写 Java 代码,那么你已经在使用构造器了,即使你可能不知道它。Java 中的所有类都有一个构造器,因为即使你没有创建构造器,Java 也会在编译代码时为你完成。但是,为了进行演示,请忽略 Java 提供的隐藏构造器(因为默认构造器不添加任何额外的功能),并观察没有显式构造器的情况。
|
||||
|
||||
假设你正在编写一个简单的 Java 掷骰子应用程序,因为你想为游戏生成一个伪随机数。
|
||||
|
||||
首先,你可以创建 dice 类来表示一个骰子。知道你玩了很久[《龙与地下城》][6],你决定创建一个 20 面的骰子。在这个示例代码中,变量 **dice** 是整数 20,表示可能的最大掷骰数(一个 20 边骰子的掷骰数不能超过 20)。变量 **roll** 是最终的随机数的占位符,**rand** 用作随机数种子。
|
||||
|
||||
|
||||
```
|
||||
import java.util.Random;
|
||||
|
||||
public class DiceRoller {
|
||||
private int dice = 20;
|
||||
private int roll;
|
||||
private [Random][7] rand = new [Random][7]();
|
||||
```
|
||||
|
||||
接下来,在 **DiceRoller** 类中创建一个函数,以执行计算机模拟模子滚动所必须采取的步骤:从 **rand** 中获取一个整数并将其分配给 **roll**变量,考虑到 Java 从 0 开始计数但 20 面的骰子没有 0 值的情况,**roll** 再加 1 ,然后打印结果。
|
||||
|
||||
|
||||
```
|
||||
public void Roller() {
|
||||
roll = rand.nextInt(dice);
|
||||
roll += 1;
|
||||
[System][8].out.println (roll);
|
||||
}
|
||||
```
|
||||
|
||||
最后,产生 **DiceRoller** 类的实例并调用其关键函数 **Roller**:
|
||||
|
||||
```
|
||||
// main loop
|
||||
public static void main ([String][9][] args) {
|
||||
[System][8].out.printf("You rolled a ");
|
||||
|
||||
DiceRoller App = new DiceRoller();
|
||||
App.Roller();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
只要你安装了 Java 开发环境(如 [OpenJDK][10]),你就可以在终端上运行你的应用程序:
|
||||
|
||||
|
||||
```
|
||||
$ java dice.java
|
||||
You rolled a 12
|
||||
```
|
||||
|
||||
在本例中,没有显式构造器。这是一个非常有效和合法的 Java 应用程序,但是它有一点局限性。例如,如果你把游戏《龙与地下城》放在一边,晚上去玩一些《快艇骰子》,你将需要六面骰子。在这个简单的例子中,更改代码不会有太多的麻烦,但是在复杂的代码中这不是一个现实的选择。解决这个问题的一种方法是使用构造器。
|
||||
|
||||
### 构造函数的作用
|
||||
|
||||
这个示例项目中的 **DiceRoller** 类表示一个虚拟骰子工厂:当它被调用时,它创建一个虚拟骰子,然后进行“滚动”。然而,通过编写一个自定义构造器,你可以让掷骰子的应用程序询问你希望模拟哪种类型的骰子。
|
||||
|
||||
大部分代码都是一样的,除了构造器接受一个表示边的数字参数。这个数字还不存在,但稍后将创建它。
|
||||
|
||||
|
||||
```
|
||||
import java.util.Random;
|
||||
|
||||
public class DiceRoller {
|
||||
private int dice;
|
||||
private int roll;
|
||||
private [Random][7] rand = new [Random][7]();
|
||||
|
||||
// 构造器
|
||||
public DiceRoller(int sides) {
|
||||
dice = sides;
|
||||
}
|
||||
```
|
||||
|
||||
模拟滚动的功能保持不变:
|
||||
|
||||
|
||||
```
|
||||
public void Roller() {
|
||||
roll = rand.nextInt(dice);
|
||||
roll += 1;
|
||||
[System][8].out.println (roll);
|
||||
}
|
||||
```
|
||||
|
||||
代码的主要部分提供运行应用程序时提供的任何参数。这的确会是一个复杂的应用程序,你需要仔细解析参数并检查意外结果,但对于这个例子,唯一的预防措施是将参数字符串转换成整数类型。
|
||||
|
||||
|
||||
```
|
||||
public static void main ([String][9][] args) {
|
||||
[System][8].out.printf("You rolled a ");
|
||||
DiceRoller App = new DiceRoller( [Integer][11].parseInt(args[0]) );
|
||||
App.Roller();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
启动这个应用程序,并提供你希望骰子具有的面数:
|
||||
|
||||
|
||||
```
|
||||
$ java dice.java 20
|
||||
You rolled a 10
|
||||
$ java dice.java 6
|
||||
You rolled a 2
|
||||
$ java dice.java 100
|
||||
You rolled a 44
|
||||
```
|
||||
|
||||
构造器已接受你的输入,因此在创建类实例时,会将 **sides** 变量设置为用户指定的任何数字。
|
||||
|
||||
构造器是编程的功能强大的组件。练习用它们来解开了 Java 的全部潜力。
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/19/6/what-java-constructor
|
||||
|
||||
作者:[Seth Kenlon][a]
|
||||
选题:[lujun9972][b]
|
||||
译者:[laingke](https://github.com/laingke)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/seth/users/ashleykoree
|
||||
[b]: https://github.com/lujun9972
|
||||
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/build_structure_tech_program_code_construction.png?itok=nVsiLuag
|
||||
[2]: https://opensource.com/resources/python
|
||||
[3]: https://opensource.com/article/17/4/pyqt-versus-wxpython
|
||||
[4]: https://opensource.com/resources/java
|
||||
[5]: https://openjdk.java.net/install/index.html
|
||||
[6]: https://opensource.com/article/19/5/free-rpg-day
|
||||
[7]: http://www.google.com/search?hl=en&q=allinurl%3Adocs.oracle.com+javase+docs+api+random
|
||||
[8]: http://www.google.com/search?hl=en&q=allinurl%3Adocs.oracle.com+javase+docs+api+system
|
||||
[9]: http://www.google.com/search?hl=en&q=allinurl%3Adocs.oracle.com+javase+docs+api+string
|
||||
[10]: https://openjdk.java.net/
|
||||
[11]: http://www.google.com/search?hl=en&q=allinurl%3Adocs.oracle.com+javase+docs+api+integer
|
Loading…
Reference in New Issue
Block a user