user1464139
user1464139

Reputation:

How to implement encapsulation in a Java class?

I am learning Java and have been given these options:

How can you implement encapsulation in a class?

  1. Make all variables protected and only allow access via methods.
  2. Make all variables private and only allow access via methods.
  3. Ensure all variables are represented by wrapper classes.
  4. Ensure all variables are accessed through methods in an ancestor class.

My choice is the second but I also would like to find out if anyone considers any other choice is correct? Also are there any other ways to implement encapsulation that are not covered here?

Upvotes: 0

Views: 4275

Answers (1)

Dmitry Zagorulkin
Dmitry Zagorulkin

Reputation: 8548

You're right. Any other method is to define an interface which will be encapsulate functionality of implementation class.

from Wikipedia:

encapsulation is:

  • A language mechanism for restricting access to some of the object's components.
  • A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

Upvotes: 1

Related Questions