|
Consider the instance methods in the Circle class definition again:
public class Circle
{
public double radius = 1; /** The radius of this circle */
public Circle() { } /** Constructor 1 for a circle object */
public Circle(double newRadius) /** Constructor 2 for a circle object */
{
radius = newRadius; // Member radius is not accessed with a ref. var !?
}
public double getArea() /** Return the area of this circle */
{
return 3.14159 * radius * radius; // Again ??
}
public void setRadius(double newRadius) /** Set new radius for this circle */
{
radius = newRadius; // Shouldn't it be: refVar.radius = newRadius ??
}
}
|
The member variable radius is not accessed using a reference variable ! How is this possible ???
Here is the dirty little secret about Java's instance methods:
|
When we define a class as follows:
public class Circle
{
public double radius = 1; /** The radius of this circle */
public Circle() { } /** Constructor 1 for a circle object */
public Circle(double newRadius) /** Constructor 2 for a circle object */
{
radius = newRadius;
}
public double getArea() /** Return the area of this circle */
{
return 3.14159 * radius * radius;
}
public void setRadius(double newRadius) /** Set new radius for this circle */
{
radius = newRadius;
}
}
|
The Java compiler will secretly insert the implicit parameter this in every instance method:
public class Circle
{
public double radius = 1; /** The radius of this circle */
public Circle(Circle this) { }
public Circle(Circle this, double newRadius)
{
radius = newRadius;
}
public double getArea(Circle this)
{
return 3.14159 * radius * radius;
}
public void setRadius(Circle this, double newRadius)
{
radius = newRadius;
}
}
|
The parameter this is a copy of the reference variable in the method invocation (E.g.: circle1.getArea())
The Java compiler will also insert this. to every member access in an instance method (and constructor):
public class Circle
{
public double radius = 1; /** The radius of this circle */
public Circle() { } /** Constructor 1 for a circle object */
public Circle(double newRadius) /** Constructor 2 for a circle object */
{
this.radius = newRadius;
}
public double getArea() /** Return the area of this circle */
{
return 3.14159 * this.radius * this.radius;
}
public void setRadius(double newRadius) /** Set new radius for this circle */
{
this.radius = newRadius;
}
}
|
We can add the
this variable
explicitly
ourselves (if you wish)
DEMO:
10-classes/08-this/Circle.java
(proof
that the parameter variable
this
exists !)
Illustrated: how the reference variable is used as the implicit parameter this and to access radius:
|
Example that illustrate the passing of the implicit parameter:
|
|
DEMO: 10-classes/09-this/Circle.java -- edit and re-compile