另一个类中的实例变量

时间:2012-03-21 02:00:46

标签: java

我正在做作业,我不会发布完整的代码,但是我坚持一些可能很简单的东西,我在书中找不到它所以我需要指向正确的方向。 我正在使用类和接口。

基本上在我的主要代码中我有这样的一行

    CheckingAccount checking = new CheckingAccount(1.0);  // $1 monthly fee

我被告知要创建一个名为CheckingAccount的类,在该类中我被告知“此类应该包含一个实例变量,用于月费,该变量初始化为传递给构造函数的值。

因为我是新手,所以这对我来说几乎不是英语,我假设所说的是收取1.00费用并在CheckingAccount类中声明它,这样我就可以使用该变量创建一个方法来计算某些东西。 / p>

soooo ......我该怎么做?我知道如何创建一个类似

的实例变量
    public double  monthly fee =
然后呢?或者我可能是错的。我真的在这个java的东西上做得很糟糕。任何帮助表示赞赏。

我想另一种问题是我只是宣称它为1.0?或者我是否“导入”该值以防它稍后更改,您不必通过代码在所有类中更改它?

4 个答案:

答案 0 :(得分:3)

您的要求(正如我所读)是在构造函数中初始化实例变量,并且您的实例化(new CheckingAccount(1.0);)显示您处于正确的轨道上。

您的课程需要的是一个构造函数方法,它接收并设置该值1.0

// Instance var declaration
private double monthly_fee;

// Constructor receives a double as its only param and sets the member variable
public CheckingAccount(double initial_monthly_fee) {
  monthly_fee = inital_monthly_fee;
}

答案 1 :(得分:3)

@Jeremy:

你很喜欢(至少,你对被要求做的事情的解释与我的解释相符);虽然我不知道班级的实际设计,或者month_fee是否需要公开,但在伪代码中你会看到类似的东西:

class CheckingAccount {  
    //Instance variable  
    double monthly_fee;    
    //Constructor
    CheckingAccount(double monthly_fee) {  
          this.monthly_fee = monthly_fee;  
    }    
    //Function to multiply instance variable by some multiplier
    //Arguments: Value to multiply the monthly fee by
    double multiply_fee(double a_multiplier) {  
          return monthly_fee*a_multiplier;  
    }  
}

答案 2 :(得分:2)

你基本上是对的。如果你还没有,你应该创建一个新类(它应该在它自己的文件,名为CheckingAccount),如下所示:

/** This is the class of Account with monthly fee. */
public class CheckingAccount {
    // This is the instance variable.
    // It should be 'private' for reasons you will surely learn soon.
    // And NOT static, since that would be a class variable, not an instance one.
    // The capitalization is called camelCase, google it up. Or, even better, find 'JavaBeans naming conventions'
    private double monthlyFee;

    // This is the constructor. It is called when you create the account.
    // It takes one parameter, the fee, which initializes our instance variable.
    // Keyword 'this' means 'this instance, this object'.
    public CheckingAccount(double monthlyFee) {
        this.monthlyFee = monthlyFee;
    }

    // Here will be your methods to calculate something...
}

答案 3 :(得分:0)

不要将实例变量创建为public。这是不好的做法,因为它违反了信息隐藏的原则(你的老师可能称之为抽象)。相反,您可以将实例变量创建为

public final class CheckingAccount {
    private double monthlyFee;

    // The rest of the class goes here

    public double getMonthlyFee() { // This method is called an accessor for monthlyFee
        return monthlyFee;
    }
}

请注意,monthly fee不是有效的变量名,因为它包含空格,变量名不能包含空格。另请注意,其他类通过方法访问monthlyFee。因为您定义方法而不是将变量设置为public,所以您可以更好地控制对monthlyFee的访问(除非您定义了进行更改的方法,否则另一个类不能只更改monthlyFee。) p>

现在访问monthlyFee。方法getMonthlyFee被称为访问者,原因如下:它允许其他类访问该变量。因此,其他类可以调用该方法来获得CheckingAccount的月费:

CheckingAccount checking = new CheckingAccount(1.0);
// A bunch of other code can go here
double fee = checking.getMonthlyFee(); // Now fee is 1.0