私は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 = apples'を使用します。 –
私はそれを試み、それは働いた。何年か前に作ったビデオの何らかの理由で、彼はこの言葉を付け加えておらず、それはまだ機能していました。 –
重要なのは 'this'キーワードではありません。重要なのは、引数をフィールドの値で初期化するのではなく、引数の値でフィールドを初期化することです。 –