【问题标题】:Assigning values to a referenced instance将值分配给引用的实例
【发布时间】:2013-05-17 20:28:04
【问题描述】:

我是一名中级 Java 初学者,对堆栈溢出也完全陌生。 (这是我的第一篇文章。)

我对以下代码以及将值分配给引用有疑问。

一、代码:

import java.awt.Point;

public class DrawPlayerAndSnake
{
  static void initializeToken( Point p, int i )
  {
    int randomX = (int)(Math.random() * 40); // 0 <= x < 40
    int randomY = (int)(Math.random() * 10); // 0 <= y < 10
    p.setLocation( randomX, randomY );
    /*
    System.out.println("The position of the player is " + playerPosition + ".");
    i = i + randomX;
    System.out.println(" i lautet " + i + ".");
    */
    Point x = new Point(10,10);
    System.out.println("The position of the x is " + x + ".");
    System.out.println("The position of the p is " + p + ".");    
    p.setLocation(x);
    x.x = randomX;
    x.y = randomY;
    p = x;
    System.out.println("The position of the p is now" + p + ".");
    System.out.println("The x position of the p is now " + p.getX() + ".");  

  }

  static void printScreen( Point playerPosition,
                       Point snakePosition )
  {
    for ( int y = 0; y < 10; y++ )
    {
      for ( int x = 0; x < 40; x++ )
      {
        if ( playerPosition.distanceSq( x, y ) == 0 )
          System.out.print( '&' );
        else if ( snakePosition.distanceSq( x, y ) == 0 )
          System.out.print( 'S' );
        else System.out.print( '.' );
      }
      System.out.println();
    }
  }

  public static void main( String[] args )
  {
    Point playerPosition = new Point();
    Point snakePosition  = new Point();

    System.out.println( playerPosition );
    System.out.println( snakePosition );
    int i = 2;
    initializeToken( playerPosition , i );
    initializeToken( snakePosition, i);

    System.out.println( playerPosition );
    System.out.println( snakePosition );

    printScreen( playerPosition, snakePosition );
  }
}      

为了教育目的而修改了这段代码(我试图理解这一点)。原始代码来自Chrisitan Ullenboom 的“Java ist auch eine Insel”一书。

好的,现在有了这个方法initializeToken,我正在传递Point 类的一个实例。 (我希望我是对的,所以如果我犯了错误,请随时纠正我。) 当这个方法被 main 方法调用时,一个对实例 playerPosition 的新引用由 Point p 创建。 现在,因为传递给方法 initializeToken 的参数 playerPosition 不是最终的,所以我可以对 p 点进行任何我想要的赋值。

但是当我使用引用变量 x 创建一个新的点对象并通过 p = x; 将此引用分配给 p 时,x playerPosition 的 y 位置不会改变,但 p.setLocation() 会改变。

谁能告诉我为什么?

【问题讨论】:

标签: java class methods reference instances


【解决方案1】:

传递给 initializeToken 的点 p 是对存储在内存中的 p 实例的本地引用。当您调用 p.setLocation() 时,您正在“取消引用”p,即修改内存中的实际实例。但是,如果简单设置 p = new Point(x, y),就是在修改 initializeToken 方法中的局部变量,一旦方法终止,局部变量就会消失。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-23
    • 2018-03-19
    • 2015-08-24
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 2016-03-12
    • 2021-12-17
    相关资源
    最近更新 更多