|
So: members in an object is always accessed through a reference variable.
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;
}
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;
}
}
|
We access the member variable radius without using any reference variable !!! How is this possible ???
Here is the dirty little secret about Java's instance methods:
|
Suppose we write the instance methods in the Circle class as:
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;
}
}
|
Remember: every instance method (and constructor) has a hidden parameter named this which is the object that invokes the instance method
The Java compiler will insert this. to every member access:
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;
}
}
|
Remember: every instance method (and constructor) has a hidden parameter named this which is the object that invokes the instance method
Example to illustrate the passing of the implicit parameter:
|
Example to illustrate the passing of the implicit parameter:
|
|
|
|
|