w*********n 发帖数: 439 | 1 If name is a String instance variable, average is a double instance variable
, and numOfStudents is a static int variable, why won’t the following code
from a class compile?
public Student(String s)
{
name = s;
average = getAverage(name);
numOfStudents++;
}
public double getAverage(String x)
{
numOfStudents++;
double ave = StudentDB.getAverage(x);
return ave;
}
public static void setAverage(double g)
{
average = g;
}
Answer
a.
The setAverage method can’t access the average instance variable.
b.
The getAverage method can’t increment the numOfStudents variable.
c.
The constructor can’t increment the numOfStudents variable.
d.
The getAverage method can’t call a static method in the StudentDB class. |
k*******6 发帖数: 103 | |
G*********e 发帖数: 56 | 3 显然是选A。
建议楼主想想java程序是怎么运行的。特别是想想你在编译完后,在执行.class文件的
时候发生了什么事情。 我是java的菜鸟。恰好最近看了一些这方面的东西。 |
z*********e 发帖数: 10149 | 4 我也觉得是a,可以考虑这么一个scenario,没有任何object的时候,调用这个ClassX.
getAverage(1.0),没有object,也就没有object的average member variable.出错了 |
n******t 发帖数: 28 | 5 你那个StudentDB.getAverage(x); 是不是打错了, 应该是StudentDB.setAverage(x); |
n******t 发帖数: 28 | 6 StudentDB.getAverage(x); 是不是写错了, 应该是StudentDB.setAverage(x);
要不然就自己调用自己了.
在一个static 方法中引用任何实例变量都是非法的, 除非你的变量都是static,或者
不要定义为static method. |
l**p 发帖数: 6080 | 7 类一实现,static进内存
average非static还没建立,无法访问
variable
code
【在 w*********n 的大作中提到】 : If name is a String instance variable, average is a double instance variable : , and numOfStudents is a static int variable, why won’t the following code : from a class compile? : public Student(String s) : { : name = s; : average = getAverage(name); : numOfStudents++; : } : public double getAverage(String x)
|