我们在java中有一个Readonly字段(可以在类本身的范围内设置)吗? [英] Do we have a Readonly field in java (which is set-able within the scope of the class itself)?

查看:1309
本文介绍了我们在java中有一个Readonly字段(可以在类本身的范围内设置)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们怎样才能在类中有一个可写的变量,但只能在其外可读?

How can we have a variable that is writable within the class but only "readable" outside it?

例如,而不是必须这样做:

For example, instead of having to do this:

Class C {
  private int width, height;

  int GetWidth(){
    return width;
  }

  int GetHeight(){
    return height;
  }

  // etc..

我想要做这样的事情:

Class C {
  public_readonly int width, height;

  // etc...

什么是最佳解决方案?

推荐答案

在Java中无法做到这一点。

There's no way to do this in Java.

你的两个选择(你提到过的一个)正在使用公共getter并将字段设为私有,或者在类中提供全面的文档。

Your two options (one which you mentioned) are using public getters and making the field private, or thorough documentation in the class.

getter方法的开销非常小(如果有的话) )。如果你这么做很多次,你可能想要缓存获取的值而不是调用get方法。

The overhead on getter methods in extremely small (if at all). If you're doing it a large number of times, you might want to cache the fetched value instead of calling the get method.

编辑:

一种方法,虽然它比getter有更多的开销,但是定义了一个公共内部类(让我们称之为 innerC )使用仅适用于 C 类的构造函数,并将字段设为公共字段。这样,您无法在班级外创建 innerC 实例,因此无法从外部更改字段,但您可以从内部更改它们。但是你可以从外面读它们。

One way to do it, although it has even more overhead than the getter, is defining a public inner class (let's call it innerC) with a constructor that is only available to your C class, and make your fields public. That way, you can't create innerC instances outside your class so changing your fields from outside is impossible, yet you can change them from inside. You could however read them from the outside.

这篇关于我们在java中有一个Readonly字段(可以在类本身的范围内设置)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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