Java OCA OCP Practice Question 3107

Question

Given the class definition:

class Point {
        public int x, y;
        public Point(int x, int y) {
                this.x = x;
                this.y = y;
        }// w w  w  . ja  v a  2  s .  c o  m
        public int getX() { return x; }
        public int getY() { return y; }
        // other methods elided
}

Which one of the following enforces encapsulation? (Select all that apply.)

  • a) Make data members x and y private
  • b) Make the Point class public
  • c) Make the constructor of the Point class private
  • d) remove the getter methods getX() and getY() methods from the Point class
  • e) Make the Point class static


a)

Note

publicly visible data members violate encapsulation since any code can modify the x and y values of a Point object directly.

It is important to make data members private to enforce encapsulation.

options b), c), and d) Making the Point class public, making the constructor of the class private or removing the getter methods will not help enforce encapsulation.

option e) You cannot declare a class static.




PreviousNext

Related