5

我正在观看Java 上的Programming Methodology (Stanford) (CS106A)课程。在 第 14 课中, Sahami教授 讲述了 Java 中用于堆栈和堆上的函数和对象的内存分配。

他告诉说,对于在对象上调用的任何方法,都会分配一个堆栈和参数列表,并且此引用会在堆栈上分配空间。通过存储的引用,Java 能够引用对象的正确实例变量。

堆栈——调用方法时

但是对于构造函数,在构造对象时,此引用与参数列表一起存储。stack -- 当构造函数被调用时

我的问题是,如果构造函数没有这个引用,那么我们如何在构造函数中使用它

public class foo {
private int i;
public foo(int i)
{this.i = i;// where this reference came from}
                 }
4

2 回答 2

1

this只是一个 Java 关键字,它允许您引用当前对象。它可以在任何课程中使用。

使用this关键字的目的是防止引用局部变量。

在您的示例中需要它,因为i = i它绝对不会做任何事情,因为两者都是对同一个局部变量(而不是类变量)的引用:

从这里

在实例方法或构造函数中,this 是对当前对象的引用——调用其方法或构造函数的对象。您可以使用 this 从实例方法或构造函数中引用当前对象的任何成员。

编辑:

我意识到您可能一直在询问实际的内存地址。

我想

class Point
{
  int x, y;
  Point(int x, int y) { this.x = x; this.y = y; }
  void move(int a, int b) { x = a; y = b; }
}
Point p = new Point(3,4);
p.move(1,2);

可能会被翻译成类似:(this明确)

class Point
{
  int x, y;
  static Point getPoint(int x, int y)
    { Point this = allocateMemory(Point); this.x = x; this.y = y; }
  static void move(Point this, int a, int b) { this.x = a; this.y = b; }
}
Point p = Point.getPoint(3,4);
Point.move(p, 1, 2);

但这一切都在一个低得多的层次上,所以它实际上看起来不会像这样,但它可能只是你思考它的一种方式。

于 2013-03-16T16:14:57.043 回答
0

所有这一切都是引用当前对象的类级别变量。
如果this不使用关键字,则该变量将存储在方法级别变量中。

public class foo {
    private int i;

    public foo(int i) {
        this.i = i; // stores the argument i into the class level variable i
    }

    public foo2(int i) {
        i = i;    // stores the argument i into the argument i
    }
}
于 2013-03-16T16:15:44.810 回答