I’m trying to understand the following valid Java code. I have two questions, which are commented in the code.
class C {
C x; //1.) why is something like x = new C(); not required here? Does this
//mean x refers to this current class of C?
int f;
void run(boolean b, int x) {
C y;
y = new C();
if (b) { this.bump(y,x); } //2.) Is "this" in this.bump necessary? Likewise,
//this.bump(this.y,x) would be equivalent right?
else { f = this.x.f + 1; }
}
void bump(C z, int j) {
z.f=j;
}
}
Thanks, sorry for such rudimentary questions
1.) why is something like x = new C(); not required here?x is only an uninitialized reference. If you want to use it, you indeed need to assign something to it.
2.) Is "this" in this.bump necessary?No.
thisrefers to the current object, and sincexis a member of the current object you do not need it in this case.2a) Likewise, this.bump(this.y,x) would be equivalent right?No.
yis a local variable, you can not access it withthis.y.