什么是C ++的const成员函数的Java等价物? [英] What is the Java equivalent of C++'s const member function?

查看:147
本文介绍了什么是C ++的const成员函数的Java等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我可以定义一个 accessor 成员函数,该函数返回私有数据成员的值(或引用),这样调用者就无法以任何方式修改该私有数据成员。 / p>

有没有办法用Java做到这一点?



如果有,怎么做?



我知道 final 关键字,但AFAIK,当应用于方法时:


  1. 防止覆盖/多态化
    子类中的方法。

  2. 使该方法内联 - 能够。(见@Joachim Sauer的评论)

但它不会限制方法返回引用到一个数据成员,以便调用者不能修改它。



我是否忽略了一些明显的东西?

解决方案

您要么返回不可变的对象,或返回私有实例变量的副本。这样,对象的内部状态被保护免于修改,即:

  private MyMutableObject mutable = ... 

public MyMutableObject getMutableObject(){
返回new MyMutableObject(this.mutable);
}
`


In C++, I can define an accessor member function that returns the value of (or reference to) a private data member, such that the caller cannot modify that private data member in any way.

Is there a way to do this in Java?

If so, how?

I know about the final keyword but AFAIK, when applied to a method it:

  1. Prevents overriding/polymorphing that method in a subclass.
  2. Makes that method inline-able. (see comment by @Joachim Sauer below)

But it doesn't restrict the method from returning a reference to a data member so that it can't modified by the caller.

Have I overlooked something obvious?

解决方案

You either return an immutable object, or return a copy of the private instance variable. This way, the object's internal state is "protected" from modification, i.e.:

private MyMutableObject mutable = ...

public MyMutableObject getMutableObject() {
   return new MyMutableObject(this.mutable);
}
`

这篇关于什么是C ++的const成员函数的Java等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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