Question 1

In the code below, there is an ambiguous reference in the constructor. The constructor is supposed to assign the value of the formal parameter to the class member variable x. Notice, however, that the formal parameter has the same name as the class member.

There is a way to get around this problem without changing either the class member variable or the formal parameter variable. Select the best answer from the choices below that would resolve this ambiguity. Note: the choices below replace the "???" in the assignment statement.

public class Point {
public int x = 0;

//constructor
public Point(int x) {
??? = x;
}
}

To resolve the ambiguity in the code, we can use the "this" keyword.

The "this" keyword in Java is used to refer to the current instance of the class, specifically to distinguish between class variables and local variables that have the same name.

In this case, we can modify the assignment statement as follows:

public Point(int x) {
this.x = x;
}

By using "this.x", we are explicitly referring to the class member variable "x", and assigning it the value of the formal parameter "x". This way, we can disambiguate between the two variables and assign the correct value to the class member.