我试图学习如何在Java中指定类构造函数.我开始明白它们指定了从该类生成的对象的实例变量的类型.它们还可用于设置实例变量的初始值.以下示例来自Sun网站上的Java教程:
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
Run Code Online (Sandbox Code Playgroud)
在你的类源代码中你应该把构造函数放在哪里?
这些参数是变量的名称吗?:(int startCadence,int startSpeed,int startGear)还是齿轮,节奏和速度变量的名称?
(int startCadence,int startSpeed,int startGear)和gear,cadence和speed之间的区别是什么?
在极少数情况下,我的导师或盐湖社区学院的任何管理员都遇到过这个问题,让我明确表达我的意图.这个问题是以最大的学术诚信精神张贴的.我要求这个问题寻求一般性的建议,并帮助理解使用Java编程语言的正确方法.我绝不会使用他人的作品,而是把它当作我自己的作品.我使用这里提供的答案作为我理解的一般帮助.我做自己的所有工作,不复制回答我的问题的人提供的工作.
Cod*_*ike 36
构造函数可以出现在类的代码中的任何位置.但是,按照惯例,大多数人将它们放在任何不是构造函数的其他函数之前.
至于变量名,所有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.
}
}
Run Code Online (Sandbox Code Playgroud)
希望有所帮助!
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在你的类源代码中你应该把构造函数放在哪里?
我使用以下内容:
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
}
Run Code Online (Sandbox Code Playgroud)
但他们可以去任何地方.我觉得最好把事情按照可见度排序.例如,我更喜欢私有方法之前的公共方法(所以如果我正在寻找一个特定的公共方法,我知道它位于文件的顶部)出于同样的原因,我通常将构造函数放在顶部.
这些参数是变量的名称吗?:
没必要,您可以根据需要命名.我通常使用相同的名称.
......还是齿轮,节奏和速度变量的名称?...
它们是实例变量名称
(int startCadence,int startSpeed,int startGear)和gear,cadence和speed之间的区别是什么?
第一个是构造函数的参数名称,前者是它自己的对象的属性的名称.
拿这个样本:
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"
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,当您将值传递给构造函数时,您正在使用参数,当您看到构造函数代码时,您会看到参数名称(接收该参数),然后将其分配给实例属性.