这个程序的流程是什么?请启发我的知识

时间:2018-12-10 09:00:10

标签: java object static this

当调用obj1.test2(obj2)时,此方法适用什么值,到底发生了什么?如果我们要交换值,那么以前和应用的值是什么?请启发我的知识

package app4;

public class T 
{
  int i;
  static void test1(T t1, T t2)
  {
    int x = t1.i;
    t1.i = t2.i;
    t2.i = x;
  }
  void test2(T t1)
  {
    int x = t1.i;
    t1.i = this.i;
    this.i = x;
  }
  public static void main(String[] args) 
  {
    T obj1 = new T(), obj2 = new T();
    obj1.i = 1;
    obj2.i = 2;
    test1(obj1, obj2);
    System.out.println(obj1.i + "," + obj2.i);
    obj1.test2(obj2);
    System.out.println(obj1.i + "," + obj2.i);
  }
}

1 个答案:

答案 0 :(得分:0)

两个方法都在对象值之间进行交换。唯一的区别是,一种方法使用两个参数,而另一种仅使用一个。您可以按照评论进行更好的理解。

public class T 
{
  int i;
  static void test1(T t1, T t2) // t1 = 1, t2 = 2
  {
    int x = t1.i;
    t1.i = t2.i;
    t2.i = x;
  }
  void test2(T t1) // t1 = 1
  {
    int x = t1.i;  
    t1.i = this.i; // 'this' is a keyword in java that is referring to the current object 
    this.i = x;    /* in our case the current object is obj1, and because the values have
                    * been swapped in the first method, this.i = 2 */
  }
  public static void main(String[] args) 
  {
    T obj1 = new T(), obj2 = new T();
    obj1.i = 1;
    obj2.i = 2;
    test1(obj1, obj2); // after returning from this method: obj1 = 2, obj2 = 1
    System.out.println(obj1.i + "," + obj2.i);
    obj1.test2(obj2); // after returning from this method: obj1 = 1, obj2 = 2
    System.out.println(obj1.i + "," + obj2.i);
  }
}