封装与数据隐藏 - Java [英] Encapsulation vs Data Hiding - Java

查看:130
本文介绍了封装与数据隐藏 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


访问者:什么是封装?如何用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.

采访者:这是数据隐藏。我们如何在Java中实现封装?

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

:uummmm

具体问题:除了'访问修饰符'之外,在Java中实现封装的方法是什么?

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

推荐答案

更一般地说,封装仅指将数据(例如对象)与对该数据的操作捆绑在一起。所以你有一个封装数据的类 - fields - 以及用于操作该数据的方法

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.

这篇关于封装与数据隐藏 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆