Consider the following class definition.
public class Example {
private int x;
// Constructor not shown.
}
Which of the following is a correct header for a method of the Example class that would return the value of the private instance variable x so that it can be used in a class other than Example ?
private int getX()
private void getX()
public int getX()
public void getX()
public void getX(int x)

Respuesta :

Answer:

public int getX()

Explanation:

From the question, we understand that the value is to be accessed in other classes.

This implies that we make use of the public access modifier. Using the public modifier will let the instance variable be accessed from other classes.

Also, we understand the return type must be the variable type of x. x is defined as integer. So, the constructor becomes public x

Lastly, we include the constructor name; i.e. getX().

Hence, the constructor is: public int getX()