zoukankan      html  css  js  c++  java
  • 传值与引用中的一道面试题

    这道题目当时自己做得时候确实做错了,而且两次都做错了,尴尬。

    Given the following code, what will be the output? 
    class Value{
      public int i = 15;
    } 
    public class Test{
      public static void main(String argv[]){
        Test t = new Test();
        t.first();

    } 
    public void first(){
      int i = 5;
      Value v = new Value();
      v.i = 25;
      second(v, i);
      System.out.println(v.i); 
    } 
    public void second(Value v, int i){
      i = 0;
      v.i = 20;
      Value val = new Value();
      v = val;
      System.out.println(v.i + " " + i);
      }
    } 
    Choices:
    a. 15 0 20   b. 15 0 15   c. 20 0 20   d. 0 15 20 

      因为对象是引用传递,first()方法将 属性i = 25 的 v对象的引用 传递给second()方法
    second()方法中首先将这个 v 的属性 i 改为 20 。然后让变量 v 指向新建的 val对象,second()方法中打印的是 val 的 属性 i(初始值15)
    在first()方法中变量 v 指向的还是原来的对象,但已经被second()方法改为20,所以打印20
    原理应该是这样 。

  • 相关阅读:
    codeforces-1139 (div2)
    codeforces-1140 (div2)
    codeforces-1141 (div3)
    第四届CCCC团体程序设计天梯赛 后记
    BZOJ 3674 可持久化并查集
    你能回答这些问题吗
    [JSOI2008]最大数
    关路灯
    愤怒的小鸟
    推销员
  • 原文地址:https://www.cnblogs.com/lzb1991/p/6509511.html
Copyright © 2011-2022 走看看