Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this reference inside the construstor

I am watching Programming Methodology (Stanford) (CS106A) course on Java . In lecture 14 Professor Sahami told about memory allocation in Java for functions and object on stack and heap .

He told that for any method called on an object , a stack is allocated and argument list and this reference is allocated space on stacke . Through this refernece stored, Java is able to refer to the correct instance variables of an object .

stack--when method is called

but for constructor no this reference is stored along with argument list as object is being constructed. stack -- when constructor is called

My ques is if constructor don't have have this refernece then how we can use it inside constructor for ex

public class foo {
private int i;
public foo(int i)
{this.i = i;// where this reference came from}
                 }
like image 659
T.J. Avatar asked Nov 12 '22 09:11

T.J.


1 Answers

this is simply a Java keyword that allows you to reference the current object. It can be used in any class.

The purpose of using the this keyword is to prevent referencing a local variable.

It is needed in your example, since i = i will do absolutely nothing, since both are references to the same local variable (not the class variable):

From here:

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

EDIT:

I realize that you may have been asking about the actual memory address.

I imagine

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);

might get translated to something like: (making this explicit)

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);

but this would all be on a much lower level, so it wouldn't actually look remotely like this, but it could just be a way for you to think about it.

like image 109
Bernhard Barker Avatar answered Nov 15 '22 07:11

Bernhard Barker