Java OCA OCP Practice Question 1718

Question

Given the following member declarations, which statement is true?.

int a;                              // (1)
static int a;                       // (2)
int f() { return a; }               // (3)
static int f() { return a; }       // (4)

Select the one correct answer.

  • (a) Declarations (1) and (3) cannot occur in the same class declaration.
  • (b) Declarations (2) and (4) cannot occur in the same class declaration.
  • (c) Declarations (1) and (4) cannot occur in the same class declaration.
  • (d) Declarations (2) and (3) cannot occur in the same class declaration.


(c)

Note

Local variables can have the same name as member variables.

The local variables will simply shadow the member variables with the same names.

Declaration (4) defines a static method that tries to access a variable named a, which is not locally declared.

Since the method is static, this access will only be valid if variable a is declared static within the class.

Therefore, declarations (1) and (4) cannot occur in the same class declaration, while declarations (2) and (4) can.




PreviousNext

Related