[英]Java parameterized constructors
我是编程新手,也是Java新手。 我现在正在尝试使用参数化构造函数,然后将创建的对象与特定方法一起使用。 这是我的代码:
public class Car {
int fuelcap;
int mpg;
Car(int f, int m) { //here
fuelcap = f; //and here
mpg = m; //and here
}
int range() {
return mpg * fuelcap;
}
public static void main(String[] args) {
Car sedan = new Car(16, 21);
Car sportscar = new Car(14, 16);
System.out.println(sedan.range());
System.out.println(sportscar.range());
}
}
问题是,我不知道为什么构造函数Car-'int f'和'int m'的参数与以下字段不同:'int fuelcap;' 'int mpg;'。 我们不能只是创建像这样的构造函数:
Car(int fuelcap, int mpg){
}
然后在创建对象时将值传递给那些参数?
你不能。 您必须将构造函数参数分配给构造函数主体中的class字段,否则将不会保存它们。 这就是Java的工作方式。 构造函数参数没有什么“神奇”的东西。
另外,请注意适当的样式:
Car(int fulecap, int mpg) {
this.fuelcap = fuelcap;
this.mpg = mpg;
}
如果您还有更多字段,那么可以使用ctor参数,就可以了。 只需将构造函数视为创建对象后调用的普通方法即可。 (最后的陈述只是一种正确的说法,但会为此目的提供正确的想法。)
是的,您当然可以,但是在那种情况下,您的构造函数应如下所示:
public Car(int fuelcap, int mpg){
this.fuelcap = fuelcap;
this.mpg = mpg;
}
您具有实例变量fuelcap
和mpg
但是如果您提到的构造函数,则它们永远不会分配给任何东西。
您可以这样做以使其更具可读性,
int fuelcap;
int mpg;
Car(int fuelcap, int mpg) {
this.fuelcap = fuelcap; //this is refrencing the instance variable in the class
this.mpg = mpg;
}
int range() {
return mpg * fuelcap;
}
构造函数无法识别您想要的方式,因为它可能导致名称相同的变量出错。
参数化构造函数用于为不同的对象提供不同的值。
如果你想使用
Car(int fuelcap, int mpg){}
您必须使用this
关键字
所以代码变成
Car(int f, int m) {
this.fuelcap = f;
this.mpg = m; }
如果您不使用this
关键字
所有对象的值将与实例变量中的值相同,即fuelcap
和mpg
现在的值为0
考虑良好做法的几点提示:
首先,您应该将成员private
( link )。 此外,将objets设置为“不可变的”是一种很好的样式,这意味着一旦创建它们,它们就无法更改状态( link )。 您可以通过将字段声明为final
来实现。
Car
类将如下所示:
public class Car
{
private final int fuelcap;
private final int mpg;
public Car( final int fuelcap, final int mpg )
{
this.fuelcap = fuelcap;
this.mpg = mpg;
}
public int range()
{
return this.mpg * this.fuelcap;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.