java - 为引用的实例赋值

标签 java class methods reference instances

我是一名中级 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”一书。

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

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

谁能告诉我为什么?

最佳答案

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

关于java - 为引用的实例赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16697662/

相关文章:

java - 基本电子邮件无法使用

java - @Access(AccessType.FIELD) 的推荐用例是什么

c++ - C++ 中的指针、类和 void*

c# - 使用字符串而不是枚举?

c - 这个 printf() 函数有多少个参数?

java - 为什么 "<= 1"没有按预期工作?

java - HashSet add(Object o) 错误

CSS - 在悬停状态下添加另一个元素

java - 重构代码以尊重 OOP 原则

Java链类