在从类构造函数调用的方法中初始化最终变量 [英] Initializing a final variable in a method called from class constructor

查看:54
本文介绍了在从类构造函数调用的方法中初始化最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我正面临着一种奇怪的行为,我不知道为什么.

Today I'm facing a strange behavior which I couldn't figure out why.

想象一下,在Java的一个典型类中,我们有一个最终变量.我们可以立即初始化它,也可以在类构造函数中将其初始化:

Imagine we have a final variable in a typical class in Java. We can initialize it instantly or in class constructor like this:

public class MyClass {

    private final int foo;

    public MyClass() {
        foo = 0;
    }
}

但是我不知道为什么我们不能在构造函数中调用方法并在该方法中初始化 foo ,就像这样:

But I don't know why we can't call a method in constructor and initialize foo in that method, like this:

public class MyClass {

    private final int foo;

    public MyClass() {
        bar();
    }

    void bar(){
        foo = 0;
    }
}

因为我认为我们仍处于构造函数流程中,所以尚未完成.任何提示将不胜感激.

Because I think we are still in constructor flow and it doesn't finished yet. Any hint will be warmly appreciated.

推荐答案

首先,编译器会在声明时为每个构造函数 复制 分配值.其次,您可以使用一种方法来初始化该值,但是您需要返回以使其生效.如其他人所述,您需要确保将此值设置为一次.

First, assigning the value at declaration time is copied into every constructor for you by the compiler. Second, you can use a method to initialize the value, but you need to return it for that to work. As others' note, you are required to ensure this value is set once.

public class MyClass {
    private final int foo = bar();

    private static int bar() {
        return 0;
    }
}

等同于

public class MyClass {
    private final int foo;

    public MyClass() {
        this.foo = bar();
    }

    private static int bar() {
        return 0;
    }
}

请注意, bar static ,因为否则您需要 instance 来调用它.

Note that bar is static, because otherwise you need an instance to call it.

这篇关于在从类构造函数调用的方法中初始化最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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