我在看一个java教程,一旦他改变他的类有构造函数而不是在每个对象中定义每个变量,他所有的方法仍然有效。为什么现在我的方法不再工作,因为我已经添加了构造函数?
我将它改为构造函数,现在我所得到的全部为0。
public class Volume3Lesson4Exercise1 {
public static void main(String[] args) {
groceryStore houstonStore = new groceryStore(534, 0.99, 429, 0.87);
groceryStore seattleStore= new groceryStore(765, 0.86, 842, 0.91);
groceryStore orlandoStore= new groceryStore(402, 0.77, 398, 0.79);
System.out.println("\nSeattle store revenue: ");
seattleStore.calculateGrossRevenue();
System.out.println("\nOrlando Store Revenue: ");
orlandoStore.calculateGrossRevenue();
}
}
class groceryStore {
int apples;
double applePrice;
int oranges;
double orangePrice;
groceryStore(int a, double ap, int o, double op){
a= apples;
ap= applePrice;
o= oranges;
op= orangePrice;
}
double calculateGrossRevenue(){
double grossRevenue;
grossRevenue= ((apples * applePrice)+ (oranges * orangePrice));
return grossRevenue;
}
}
在以下代码中,收入返回数字0作为总收入。为什么?数字与以前一样,但现在只是构造函数而不是每个对象的单个变量。
变化'一个= apples'到'this.apples = A'。当然,其他领域也一样。通常的惯例是为参数和字段使用相同的名称,并使用'this.apples = apples'。 –
我试过了,它工作。出于某种原因,在几年前某人拍摄的视频中,他没有添加这个词,它仍然有效。 –
重要的不是'这个'关键字。重要的是,您使用参数的值初始化字段,而不是使用字段的值初始化参数。 –