简体   繁体   English

没有getter setter方法的Java封装

[英]Java Encapsulation without getter setter methods

Can we achieve encapsulation in java without having any getter or setter methods? 我们可以在没有任何getter或setter方法的情况下实现Java封装吗?

For example, the code below 例如,下面的代码

class A {

  private int id;
  private String name;

}

Can we say that above code satisfies encapsulation? 我们可以说上述代码满足封装要求吗?

Sure, you can say that this class satisfies encapsulation. 当然,您可以说此类满足封装要求。 It does not expose internal state or implementation. 它不公开内部状态或实现。 If you add method that will use these fields it is encapsulation in action. 如果添加将使用这些字段的方法,则它实际上是封装。 The main idea of encapsulation is to hide internal implementation from the user of the class. 封装的主要思想是向类用户隐藏内部实现。

Partially, Actually there is literally no use of the code that you presented but making all the variables private alone will not make that an encapsulation. 部分地,实际上,实际上没有使用您提供的代码,但仅将所有变量设为私有不会封装。

Encapsulation means "binding the data and data members together" means joining data and methods related to that data in a class to form an encapsulated object. 封装是指“将数据和数据成员绑定在一起”是指将数据和与该数据相关的方法归为一类,以形成封装的对象。

And also to hide the direct usage of data members!. 并且还隐藏了数据成员的直接用法!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM