【发布时间】:2010-11-14 16:14:38
【问题描述】:
我写了一个小类来创建一个包含 3 个数组的报表对象。在创建对象时,这些数组用值初始化。但是,当我测试该类以查看部门数组中的内容时,它会打印出数组元素为空。为什么?
class Report
{
// declare instance variables (arrays)
public String[] departments = new String[4] ;
public double[] grossTotals = new double[4] ;
public double[] taxTotals = new double[4] ;
// constructor
public Report(){
// declare, create and initialise all in one statement
String[] departments = {"Accounting", "Sales", "HR", +
"Administration"} ;
double[] grossTotals = {0.0, 0.0, 0.0, 0.0} ;
double[] taxTotals = {0.0, 0.0, 0.0, 0.0} ;
} // END constructor
} // class Report
测试类:
class TestReport
{
public static void main(String[] args) {
// create report object
Report r = new Report();
for (int i = 0; i <= 3 ; i++ )
{
System.out.println(r.departments[i]) ;
}
} //end main
} // end test class
谢谢
爸爸
【问题讨论】:
-
顺便说一句,公开数组(如在 public String[] 中)是一个坏习惯。其他代码现在可以更改这些数组。即使
public final也不能解决这个问题,因为内容仍然可以更改。对于数组,最好尽可能将它们设为私有(也可能是static final)。 -
嗨,谢谢,这是正确的。但是,我需要一个 getter 方法来从我的示例没有的测试类中检索数据。