[关闭]
@w1024020103 2017-02-09T20:00:35.000000Z 字数 1008 阅读 694

week2 2.3 2.4 notes

CS61B UCBerkeley

discussion 2:
Pass by what?
Consider the following code block:

  1. public class Pokemon {
  2. public String name;
  3. public int level;
  4. public Pokemon(String name, int level) {
  5. this.name = name;
  6. this.level = level;
  7. }
  8. public static void main(String[] args) {
  9. Pokemon p = new Pokemon("Pikachu", 17);
  10. int level = 100;
  11. change(p, level);
  12. System.out.println("Name: " + p.name + ", Level: " + p.level);
  13. }
  14. public static void change(Pokemon poke, int level) {
  15. poke.level = level;
  16. level = 50;
  17. poke = new Pokemon("Gengar", 1);
  18. }
  19. }

a) What will be printed out by the code above?
Name: Pikachu, Level: 100( first time I got this wrong as 17)
b) Draw a box and pointer diagram to illustrate what happened.
Visualizer Link
c) On line 19, we set level equal to 50. What level do we mean? An instance variable of the Pokemon class? The local variable containing the parameter to the change method? The local variable in the main method? Or something else?
It is the local variable in the change method and does not have any effect on the other variables of the same name (such as in the Pokemon class or in the main method)

Check out the visualizer to thoroughly understand what in fact is going on behind the scene

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注