Given the code fragment
class Test2 {
int fvar;
static int cvar;
public static void main(String[] args) {
Test2 t = new Test2();
// insert code here to write field variables
}
}
Which code fragments, inserted independently, enable the code compile?
A.
t.fvar = 200;
B.
cvar = 400;
C.
fvar = 200;
cvar = 400;
D.
this.fvar = 200;
this.cvar = 400;
E.
t.fvar = 200;
Test2.cvar = 400;
F.
this.fvar = 200;
Test2.cvar = 400;
题解
选项 A,用对象实体的参考变量去访问对象实体的字段,这个正确。
选项 B,直接在静态方法「main」里面使用静态的字段,这个也正确。
选项 C,直接在静态方法「main」里访问对象实体的字段,因为没有对象,所以无法访问。
选项 D,直接在静态方法「main」里使用「this」来表示目前的对象实体,因为没有对象,所以无法访问。
选项 E,用对象实体的参考变量去访问对象实体的字段,和用类别名称去访问类别字段,这个也正确。
选项 F,不能使用「this」,理由同选项 D。
