public class Foo {
public int x;
public int y;
public Foo(int a) {
x = a;
y = 1;
}
public int bar(int a) {
x += a;
y += 1;
return (x + y);
}
public void bar(Foo f) {
if (f.x < x) {
f.bar(x);
} else {
bar(f.x);
}
}
}
Fill in the table based on the following
1: Foo f1 = new Foo(1);
2: Foo f2 = new Foo(2);
3: f1.bar(3);
4: f2.bar(4);
5: f1.bar(f2.bar(5));
6: f2.bar(f1);
7: f1.bar(new Foo(6));
So we are going to walk through the values after every call.
By the time we get to line 3 we have the following information
Line # | f1.x | f1.y | f2.x | f2.y |
---|---|---|---|---|
start | 1 | 1 | 2 | 1 |
Line 3 gets executed: f1.bar(3);
f1
variblebar(3)
is called. so x
gets increased by 3 and y
by 1Line # | f1.x | f1.y | f2.x | f2.y |
---|---|---|---|---|
3 | 4 | 2 | 2 | 1 |
Line 4: f2.bar(4);
f2
variable nowbar(4)
is called. so x
gets increased by 4 and y
by 1Line # | f1.x | f1.y | f2.x | f2.y |
---|---|---|---|---|
4 | 4 | 2 | 6 | 2 |
line 5: f1.bar(f2.bar(5));
f2.bar(5)
f2
variablex
increases by 5 and y
by 1f2
: x = 11 and y = 3(x + y)
== 14f1.bar(14)
f1
variablex
increases by 14 and y
by 1f1
: x = 18 and y = 3Line # | f1.x | f1.y | f2.x | f2.y |
---|---|---|---|---|
5 | 18 | 3 | 11 | 3 |
Line 6: f2.bar(f1);
Foo
object.f1.x < f2.x
we then call f1.bar(f2.x);
f2.bar(f1.x);
else
block
f2.bar(f1.x);
f2
and increase its x
by f1.x
and increase
y
by 1
Line # | f1.x | f1.y | f2.x | f2.y |
---|---|---|---|---|
6 | 18 | 3 | 29 | 4 |
line 7: f1.bar(new Foo(6));
Foo
has an x = 6 and y = 1;newfoo.x < f1.x
we then call newfoo.bar(f1.x);
f1.bar(newfoo.x);
if
block. The if
block modifies the object newfoo
that we made but this object has no impact on us and is discarded after the expression is returned. So it
doesn’t change f1
or f2
Line # | f1.x | f1.y | f2.x | f2.y |
---|---|---|---|---|
7 | 18 | 3 | 29 | 4 |