Java 构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/579445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Constructors
提问by Patrick Cassell
I am trying to learn how to specify class constructors in Java. I am starting to understand that they specify the types of instance variables of objects made from that class. They also can be used to set the instance variable initial values. The follow example is from the Java tutorial on Sun's website:
我正在尝试学习如何在 Java 中指定类构造函数。我开始明白他们指定了由该类创建的对象的实例变量的类型。它们还可用于设置实例变量的初始值。以下示例来自 Sun 网站上的 Java 教程:
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
Where in your classes source code should you put the constructor(s)?
您应该将构造函数放在类源代码的什么位置?
Are these arguments the names of the variables?: (int startCadence, int startSpeed, int startGear) or are gear, cadence and speed the names of the variables?
这些参数是变量的名称吗?: (int startCadence, int startSpeed, int startGear) 还是 gear、cadence 和 speed 是变量的名称?
What is the difference between (int startCadence, int startSpeed, int startGear) and gear, cadence and speed?
(int startCadence, int startSpeed, int startGear) 和 gear、cadence 和 speed 有什么区别?
In the unlikely event that my instructor or any administrator from Salt Lake Community College ever comes across this question, let me make my intentions clear. This question is posted in the greatest spirit of academic honesty. I ask this question to seek general advice and help in understanding the proper way to use the Java programming language. I in no way use the work of others and represent it as my own work. I use the answers provided here as a general aid in my understanding. I do all my own work and do not copy work provided by people answering my question.
万一我的导师或盐湖社区学院的任何管理员遇到这个问题,让我明确我的意图。这个问题是本着最大的学术诚信精神发布的。我问这个问题是为了寻求一般建议并帮助理解使用 Java 编程语言的正确方法。我绝不会使用他人的作品并将其呈现为我自己的作品。我使用这里提供的答案作为我理解的一般帮助。我做我自己的所有工作,不会复制回答我问题的人提供的工作。
采纳答案by CodingWithSpike
The constructors can appear anywhere in the code for the class. However, by convention, most people put them before any other functions that aren't constructors.
构造函数可以出现在类的代码中的任何位置。但是,按照惯例,大多数人将它们放在任何其他不是构造函数的函数之前。
As for the variable names, all 6 are actually variable names, but the scope is differnet. The ones specified as parameters to the constructor (startCadence, startSpeed, startGear) are only available within the constructor. The other 3 (gear, cadence, speed) are probably class-wide variables, available to all methods. However the definition isn't shown in your code snippet. The full class would look mroe like:
至于变量名,6个其实都是变量名,只是作用域不同。指定为构造函数参数的那些(startCadence、startSpeed、startGear)仅在构造函数中可用。其他 3 个(齿轮、节奏、速度)可能是类范围的变量,可用于所有方法。但是,定义未显示在您的代码片段中。完整的类看起来像:
class Bicycle
{
// class-level variables
private int gear;
private int cadence;
private int speed;
// constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// another method (not a constructor)
public void ShiftUp() {
gear = gear + 1; // notice the 'gear' variable is available here too.
}
}
Hope that helps!
希望有帮助!
回答by Fortyrunner
You really need a copy of Head First Java
你真的需要一份Head First Java
回答by Michael Myers
- It's totally up to you. I usually start with all variables, then constructors, then methods, but it's just personal preference.
- The names of the arguments are completely irrelevant, as long as you don't name them the same thing as your variables. In this example,
gear
,cadence
, andspeed
are the variables. - You are (or somebody is) passing three
ints
to the constructor. The names (startCadence
,startSpeed
, andstartGear
are called the formal parameters, and they are the way you can identify the arguments. See http://en.wikipedia.org/wiki/Parameter_(computer_science).gear
,cadence
, andspeed
are defined somewhere else in the class. Any method in the class can refer to them.
- 这完全取决于你。我通常从所有变量开始,然后是构造函数,然后是方法,但这只是个人喜好。
- 参数的名称完全无关紧要,只要您不将它们命名为与变量相同的名称。在此示例中
gear
,cadence
、 和speed
是变量。 - 您正在(或有人)将三个传递
ints
给构造函数。名字(startCadence
,startSpeed
和startGear
被称为形式参数,他们是可以识别的参数的方式。见http://en.wikipedia.org/wiki/Parameter_(computer_science) 。gear
,cadence
以及speed
在被定义在别处类中的任何方法都可以引用它们。
Don't worry--if you work at it, this sort of thing will be second nature pretty soon.
别担心——如果你努力工作,这种事情很快就会成为第二天性。
Oh, and may I suggest that you get a good IDE? BlueJis supposed to be good for beginners, and NetBeansand Eclipsefor more experienced programmers. Source code highlighting can be invaluable.
哦,我可以建议你得到一个好的 IDE 吗?BlueJ应该适合初学者,而NetBeans和Eclipse适合更有经验的程序员。源代码突出显示是无价的。
回答by Powerlord
I generally put my constructors up near the top of my file, after package, import, Javadoc, and static/instance variable declaration sections.
我通常将构造函数放在文件顶部附近,在包、导入、Javadoc 和静态/实例变量声明部分之后。
gear, cadence, and speed are the class variables, presumably defined outside of the constructor somewhere. startCadence, startSpeed, and startGear are also variables, but they are the parameters passed to the constructor.
gear、cadence 和 speed 是类变量,大概是在构造函数之外的某个地方定义的。startCadence、startSpeed 和 startGear 也是变量,但它们是传递给构造函数的参数。
You may also see something like this:
您可能还会看到类似这样的内容:
public Bicycle(int cadence, int speed, int gear) {
this.gear = gear;
this.cadence = cadence;
this.speed = speed;
}
which sets the class variables from the parameters of the same name.
它从同名的参数设置类变量。
回答by basszero
gear, cadence and speed are member variables of the class (declared elsewhere) and startCadence, startSpeed, and startGear are function parameters.
gear、cadence 和 speed 是类的成员变量(在别处声明),startCadence、startSpeed 和 startGear 是函数参数。
class Bicycle
{
private int gear, cadence, speed;
public Bicycle(int startCadence, int startSpeed, int startGear)
{
// set the value of member variables from passed parameters
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
}
回答by benjismith
Actually, the arguments to a constructor don't have to stored as the object's member variables. Here's an example:
实际上,构造函数的参数不必存储为对象的成员变量。下面是一个例子:
class NumberAsString {
private String numAsStr;
public NumberAsString(double number) {
this.numAsStr = Double.toString(number);
}
}
In this example, the constructor argument isn't actually stored anywhere, but its value is necessary for the calculation of one or more member variable values.
在此示例中,构造函数参数实际上并未存储在任何地方,但它的值对于计算一个或多个成员变量值是必需的。
The behavior you've seen, where all the arguments are stored directly as member variables, is pretty common. Especially for certain kinds of classes that simply provide "getter" and "setter" methods for their member variables (without offering any calculation or transformation functions). In the java world, these kinds of classes are commonly referred to as "beans". (Which, yes, is a very stupid name.)
您所看到的所有参数都直接存储为成员变量的行为非常常见。特别是对于某些只为其成员变量提供“getter”和“setter”方法的类(不提供任何计算或转换函数)。在 Java 世界中,这些类通常被称为“bean”。(是的,这是一个非常愚蠢的名字。)
回答by Berend Vervelde
The basic difference between int startCadence and cadence is not in the variables, but in their scope. If a variable is defined inside a method, like a constructor, it will only exist inside this method, but not outside. If a variable is defined in a class, it will exist everywhere in that class, such a variable has a global scope. The variable startCadence wll only exist inside the constructor, so if you want to use it's value elsewhere, you can pass it to another variable with a global scope. This is what happens here: cadence = startCadence;
int startCadence 和cadence 之间的基本区别不在于变量,而在于它们的范围。如果变量定义在方法内部,例如构造函数,则它只会存在于该方法内部,而不会存在于外部。如果在一个类中定义了一个变量,它就会存在于该类中的任何地方,这样的变量具有全局作用域。变量 startCadence 将只存在于构造函数中,所以如果你想在其他地方使用它的值,你可以将它传递给另一个具有全局作用域的变量。这就是这里发生的事情:cadence = startCadence;
回答by OscarRyz
Where in your classes source code should you put the constructor(s)?
您应该将构造函数放在类源代码的什么位置?
I use the following:
我使用以下内容:
package statement ....
import statements....
public class MyClass {
// instance attributes
private int i;
// class attribute
private static int MAX;
// static methods
public static int getClassCount() {
}
// Constructor!!
public MyClass() { // constructor.
}
// public methods
// protected methods
// private methods
// public static void main
}
But they can go anywhere. I feel it is better yo put things in order of visibility. For instance I rather have the public methods before the private methods ( so if I'm looking for an specific public method I know it's at the top of the file ) For the same reason I usually put the constructor at the top.
但他们可以去任何地方。我觉得按照可见性的顺序排列会更好。例如,我宁愿在私有方法之前使用公共方法(因此,如果我正在寻找特定的公共方法,我知道它位于文件的顶部)出于同样的原因,我通常将构造函数放在顶部。
Are these arguments the names of the variables?:
这些参数是变量的名称吗?:
Not necessary, you can name them as you want. I usually use the same name.
没有必要,您可以随意命名它们。我通常使用相同的名称。
...or are gear, cadence and speed the names of the variables?...
...或者齿轮、节奏和速度是变量的名称吗?...
They are the instancevariable names
它们是实例变量名
What is the difference between (int startCadence, int startSpeed, int startGear) and gear, cadence and speed?
(int startCadence, int startSpeed, int startGear) 和 gear、cadence 和 speed 有什么区别?
The first are the parameter names for the constructor and the former are the names of the attributes of the object it self.
第一个是构造函数的参数名称,前者是对象自身的属性名称。
Take this other sample:
拿这个其他样本:
public class Person {
private String name; // a person has a name.
public Person( String nameParameter ) {
this.name = nameParameter;
}
public String toString() {
return "My name is : " + this.name;
}
public static void main( String [] args ) {
// creates a new "instance" and assign "Patrick" as its name.
Person one = new Person("Patrick");
System.out.println( one ); // prints "My name is: Patrick"
// each person have its own name.
Person two = new Person("Oscar");
System.out.println( two ); // prints "My name is: Oscar"
}
}
As you see, when you pass a value to the constructor you're using an argument, and when you see the constructor code you see the parameter name ( which receives that argument ) and then it is assigned to the instance attribute.
如您所见,当您将值传递给构造函数时,您正在使用一个参数,当您看到构造函数代码时,您会看到参数名称(接收该参数),然后将其分配给实例属性。
回答by OscarRyz
The (int startCadence, int startSpeed, int startGear)
parameters are the constructor arguments and they will set the Bicycle fields cadence
, speed
, and gear
. They are available only within the constructor. gear
, cadence
, and speed
are instance variables unique for each Bicycle instance and referencable from other methods.
The constructor arguments allow you to provide parameters for the initialization of an object. In this example, you can create a Bicycle object with a gear of 1, cadence of 0, and a speed of 0 like so:
该(int startCadence, int startSpeed, int startGear)
参数构造函数的参数,他们将设置自行车场cadence
,speed
和gear
。它们仅在构造函数中可用。gear
、cadence
和speed
是每个 Bicycle 实例唯一的实例变量,可从其他方法引用。构造函数参数允许您为对象的初始化提供参数。在此示例中,您可以创建一个齿轮为 1、节奏为 0、速度为 0 的自行车对象,如下所示:
Bicycle bike = new Bicycle(0, 0, 1);
Or you can create a moving Bicycle where the cadence is 60 rpm, and the speed is 10 mph, at 3rd gear like so:
或者,您可以创建一个移动自行车,其中踏频为 60 rpm,速度为 10 mph,在 3 档,如下所示:
Bicycle bike = new Bicycle(60, 10, 3);
The placement of the constructor is irrelevant but usually constructors are placed in the beginning of the class definition.
构造函数的位置无关紧要,但通常构造函数放置在类定义的开头。
回答by Allan S
1) The location of the constructor doesn't matter in the slightest. Going by convention, however, I would personallyplace it as follows:
1)构造函数的位置一点也不重要。但是,按照惯例,我个人将其放置如下:
public class Bicycle {
public int gear, cadence speed;
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
public void otherFunction1() {}
public void otherFunction2() {}
public void otherFunction3() {}
}
2) gear, cadence, and speed are member variables of the class; they belong to each Bicycle, and are different variables for each Bicycle. startCadence, startSpeed, and startGear, however, are local variables, which only belong in that function. When I call for a
2)gear、cadence、speed是类的成员变量;它们属于每辆自行车,并且是每辆自行车的不同变量。但是,startCadence、startSpeed 和 startGear 是局部变量,只属于该函数。当我要求一个
new Bicycle(10, 15, 5);
startCadence is set to 10, startSpeed is set to 15, and startGear is set to 5. Then, the constructor initializes the member variables to their "start" corresponding variables.
startCadence 设置为 10,startSpeed 设置为 15,startGear 设置为 5。然后,构造函数将成员变量初始化为其“start”对应的变量。