在Java中相当于const(C ++) [英] Equivalent of const(C++) in Java

查看:436
本文介绍了在Java中相当于const(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Java中是否有相当于c ++的const。我理解final关键字,但不幸的是我不能使用它来声明一个函数的返回值final。

I was wondering if there was an equivalent to c++'s const in Java. I understand the final keyword, but unfortunately I cannot use that to declare a functions return value final. Instead, it always ensures the function cannot be overridden, correct?

基本上,我想确保一个给定的返回类不能被修改并且是只读的。这是可能在Java吗?

Basically, I want to make sure a given returned class cannot be modified and is read only. Is that possible in Java?

推荐答案


基本上,我想确保一个给定的返回类不能be
修改并且是只读的。这是可能在Java吗?

Basically, I want to make sure a given returned class cannot be modified and is read only. Is that possible in Java?

不直接,但一个解决方法是 不可变对象

Not directly, but one workaround is an immutable object.

示例 -

public final Foo{

    private final String s;

    public Foo(String s){
        this.s = s;
    }

    // Only provide an accessor!
    public String getString(){
        return s;
    }
}

这篇关于在Java中相当于const(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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