Encapsulating the Vehicle Class - Java SE 8 Programmer II Exam

Encapsulating the Vehicle Class

Question

Given the definition of the Vehicle class: class Vehicle{ String name; void setName (String name){ this.name = name; } String getName(){ return name; } } Which action encapsulates the Vehicle class?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D. E. F.

D.

Encapsulation is one of the fundamental concepts in object-oriented programming. It means that data and behavior are enclosed within a class, and access to that data and behavior is restricted to only the class itself. Encapsulation helps to achieve data abstraction, data hiding, and access control.

In the given code snippet, the Vehicle class has a private instance variable name, a public method setName() to set the value of the name variable, and a public method getName() to retrieve the value of the name variable.

To encapsulate the Vehicle class, the data (i.e., the name variable) should be hidden from the outside world, and access to that data should be restricted. This can be achieved by making the name variable private, so that it can only be accessed within the class.

Therefore, the correct answer is (D) Make the name variable private.

Option (A) Make the Vehicle class public is not related to encapsulation. Making a class public means that it can be accessed from other classes.

Option (B) Make the name variable public violates the principle of encapsulation, as it exposes the internal state of the Vehicle class to the outside world.

Option (C) Make the getName() method public is fine since it provides controlled access to the private variable, name.

Option (E) Make the setName() method private would make it impossible to set the value of the name variable from outside the class, violating the principle of encapsulation.

Option (F) Make the getName() method private would make it impossible to retrieve the value of the name variable from outside the class, violating the principle of encapsulation.