2017-04-13 36 views
0

我在看一个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作为总收入。为什么?数字与以前一样,但现在只是构造函数而不是每个对象的单个变量。

+5

变化'一个= apples'到'this.apples = A'。当然,其他领域也一样。通常的惯例是为参数和字段使用相同的名称,并使用'this.apples = apples'。 –

+0

我试过了,它工作。出于某种原因,在几年前某人拍摄的视频中,他没有添加这个词,它仍然有效。 –

+0

重要的不是'这个'关键字。重要的是,您使用参数的值初始化字段,而不是使用字段的值初始化参数。 –

回答

2

值的构造函数中的分配必须改变顺序,即

groceryStore(int a, double ap, int o, double op) { 
    apples = a; 
    applePrice = ap; 
    oranges = o; 
    orangePrice = op; 
} 

这样做将意味着,传递给构造函数的参数值将被保存在实例变量(苹果,applePrice等等),这是预期的行为。原始代码中显示的分配无效,因此实例变量将保留其默认值,即所有数字的0

为了更清楚,该this关键字应被用于所有的实例变量,即

groceryStore(int a, double ap, int o, double op) { 
    this.apples = a; 
    this.applePrice = ap; 
    this.oranges = o; 
    this.orangePrice = op; 
} 
+0

究竟是什么意思?当我创建每个对象时,我在顶部分配了所有的值。那么,他们为什么还是0呢?这是没有道理的。 –

+3

它们保持为'0',因为没有值实际分配给实例变量。分配总是发生在'='符号左侧的参数上。查看构造函数中'='左边的变量。例如,你在第一次调用时将'534'传递给'a',并且在构造函数中由'apples'覆盖了'''',因为你定义了'a = apples'(意思是“赋予'a' “),因此'534'永远不会被分配给'苹果';相反,'a'获得'apples'的值,这是默认值,即'0',因为之前没有赋值。 – PNS

+0

关于构造函数教的视频没有使用这个词,他们仍然工作。我添加了这个词,他们都工作。 –

相关问题