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 .
but for constructor no this reference is stored along with argument list as object is being
constructed.
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}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With