Scopes
/** Representing circles.
*/
public class Circle {
private double radius;
/** Creating a circle.
* @param r representing the circle's radius
*/
public Circle(double r) {
radius = r;
}
public double getDiameter() {
return 2 * radius;
}
}
/** Representing circles.
*/
public class Circle {
private double radius;
/** Creating a circle.
* @param radius Circle's size
*/
public Circle(double radius) {
radius = radius; // Warning: Variable 'radius' is assigned to itself.
}
public double getDiameter() {
return 2 * radius;
}
}
No. 98
Constructors variable names and “this”.
Q: |
Currently our constructor is being implemented as:
This imposes problems with respect to proper documentation. A developer will try to choose reasonable variable names clearly indicating the desired purpose like “age” and “salary”. The ratio for choosing “ageValue” and “salaryValue” originates from the need to resolve instance from method scope thereby avoiding shadowing of variable names. From the viewpoint of code comprehensibility we prefer:
This compiles correctly but yields two warnings: The
constructor argument variables Apparently we are missing something. Explain these two compiler warnings. How can the underlying conflict be resolved? TipRead the section in [Kurniawan] about the “this” keyword and the class vs. method scope slide. |
A: |
When choosing
Within the constructor's method body the parameter list
scope will take precedence over instance
scope. Thus the assignment We may explicitly resolve this scope conflict in our
favour by qualifying the instance variables public Employee(int age, double salary) { // The "this" keyword refers to class scope this.age = age; this.salary = salary; } |