2009年2月6日 星期五

第40題

Given:
1. class Foo{
2. private int x;
3. public Foo(int x){this.x = x;}
4. public void setX(int x){this.x = x;}
5. public int getX(){return x;}
6. }
7.
8. public class Gamma{
9. static Foo fooBar(Foo foo){
10. foo = new Foo(100);
11. return foo;
12. }
13. public static void main(String[] args){
14. Foo foo = new Foo(300);
15. System.out.print(foo.getX() + "-");
16.
17. Foo fooFoo = fooBar(foo);
18. System.out.print(foo.getX() + "-");
19. System.out.print(fooFoo.getX() + "-");
20.
21. foo = fooBar(fooFoo);
22. System.out.print(foo.getX() + "-");
23. System.out.print(fooFoo.getX());
24. }
25. }
What is the output?
A. 300-100-100-100-100
B. 300-300-100-100-100
C. 300-300-300-100-100
D. 300-300-300-300-100

---------------------------------------------------------------------------
答案:B
參考:6-2 Java方法、8-2 方法種類與呼叫方式

物件參照到實體的觀念
8. public class Gamma{
9. static Foo fooBar(Foo foo){
10. foo = new Foo(100);
11. return foo;
12. }
13. public static void main(String[] args){
14. Foo foo = new Foo(300);
15. System.out.print(foo.getX() + "-"); //300-
16.
17. Foo fooFoo = fooBar(foo);
18. System.out.print(foo.getX() + "-"); //300-
19. System.out.print(fooFoo.getX() + "-"); //100-
20.
21. foo = fooBar(fooFoo);
22. System.out.print(foo.getX() + "-"); //100-
23. System.out.print(fooFoo.getX()); //100
24. }
25. }

沒有留言:

張貼留言