在Java的封装中,我们可以将一个方法设为私有吗?

huangapple go评论60阅读模式
英文:

can we make a method as private in encapsulation in java?

问题

为了实现封装,我们将成员设为私有(变量),并使用getter和setter方法进行数据隐藏,这就是我们实现数据隐藏的方式。那么同样的方式,我们能否将方法设为私有,并通过getter或setter方法访问它?(或者是否有其他方法可以实现这一点)

英文:

To achieve encapsulation we make members as private (variables) and use getter and setter methods for data hiding and that's how we achieve data hiding. So in the same way can we make a method as private and access it with getter or setter method ? (or is there any other way to do it)

答案1

得分: 1

在Java中,private方法是具有私有访问修饰符的方法,仅限于在定义类内部访问,不对其子类可见,因此不具备重写的资格。然而,我们可以在子类中定义一个同名方法,并且可以在父类中访问。
基于同样的理由,我认为不能有getter和setter方法。

英文:

In Java private methods are the methods having private access modifier and are restricted to be accessed in the defining class only and are not visible in their child class due to which are not eligible for an override. However, we can define a method with the same name in the child class and could access in the parent class.
I don't think there can be getters and setters method for the same reason.

答案2

得分: 1

当然可以将一个方法定义为 private,这样它只能从同一类中的其他方法(实质上)调用。这是一个相当常见的做法。例如,我可以提供一个名为 getFoo() 的方法,其中 foo 的实际值不仅仅是一个实例变量,而是通过使用其他(私有)方法进行计算得出的。对于该类的用户来说,getFoo() 返回名为 'foo' 的某些数据,但它无法看到数据的来源——无论它是存储的、派生的还是某种组合。

英文:

Certainly you can define a method as private, so that it can only be called (essentially) from other methods in the same class. This is a pretty common practice. For example, I might provide a method getFoo(), where the actual value of foo is not not simply an instance variable, but something derived by calculation using other (private) methods. To the user of the class, getFoo() returns some data called 'foo', but it can't see where it comes from -- whether it's stored, or derived, or some combination.

huangapple
  • 本文由 发表于 2020年9月9日 22:17:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63813589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定