Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
830 views
in Technique[技术] by (71.8m points)

oop - Encapsulation vs Data Hiding - Java

Interviewer: What is encapsulation and how do you achieve it in Java?

Me: Encapsulation is a mechanism to hide information from the client. The information may be data or implementation or algorithm. We achieve this using access modifiers.

Interviewer: This is data hiding. How do we achieve encapsulation in Java?

Me: uummmm

Concrete Question: Other than 'Access Modifiers', what is the way to implement Encapsulation in Java?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

More generally encapsulation refers simply to bundling the data (e.g. of an object) with the operations on that data. So you have a class encapsulating data - fields - along with the methods for manipulating that data.

But encapsulation is also sometimes used in the same way as your answer, and indeed, one of the points of bundling data and methods is to hide the implementation.

I suppose a better answer than just use methods and make all fields private is: use interfaces. This way, operations on an object are purely based on the interface contract, and are in no way tied to the fields or helper methods used to implement that contract internally.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...