在Java中的构造函数之前初始化最终变量 [英] Initialize final variable before constructor in Java

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

问题描述

有没有解决方案在Java构造函数中使用最终变量?
问题是,如果我初始化一个最终字段,如:

Is there a solution to use a final variable in a Java constructor? The problem is that if I initialize a final field like:

private final String name = "a name";

那么我不能在构造函数中使用它。 Java首先运行构造函数,然后运行字段。有没有解决方案允许我访问构造函数中的最后一个字段?

then I cannot use it in the constructor. Java first runs the constructor and then the fields. Is there a solution that allows me to access the final field in the constructor?

推荐答案

我真的不理解你的问题。

I do not really understand your question. That

public class Test3 {
    private final String test = "test123";

    public Test3() {
        System.out.println("Test = "+test);
    }

    public static void main(String[] args) {
        Test3 t = new Test3();
    }
}

执行如下操作:

$ javac Test3.java && java Test3
Test = test123

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

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