Java OCA OCP Practice Question 436

Question

Consider the following class:

public class Test{ 
    public int id; 
} 

Which of the following is the correct way to make the variable 'id' read only for any other class?

Select 1 option

  • A. Make 'id' private.
  • B. Make 'id' private and provide a public method getId() which will return its value.
  • C. Make 'id' static and provide a public static method getId() which will return its value.
  • D. Make id 'protected'


Correct Option is  : B

Note

A. is wrong. This will not allow others to read or write.

B. is a standard way of providing read only access to internal variables.




PreviousNext

Related