java - 如何从另一个调用一个空的构造函数?

标签 java constructor

我有一些这样的代码:

public class Foo {
    private int x;

    public Foo() {
    }

    public Foo(int x) {
        try {
            //do some initialisation stuff like:
            this.x = x;
        }
        catch(Exception ge){
            //call empty constructor not possible
            //this();
            //this.EMPTY();
            //Foo();
        }
    }

    public static final Foo EMPTY = new Foo();
}

我想知道是否有可能实现这样的事情(我知道调用另一个构造函数必须是构造函数中的第一条语句)。 我在 SO 上四处查看,但没有找到任何类似的东西,这让我相信也许我应该在实例化方法中处理错误逻辑。

最佳答案

只需更改执行顺序:

public class Foo {

    Integer i;
    public Foo() {
        System.out.println("Empty constructor invoked");
    }

    public Foo(Integer i) {

        this(); //can be omitted

        try {
            System.out.println("i initialized to : "+i.toString());

        } catch (Exception ex) {

            System.out.println("i NOT initialized ");
        }
    }


    public static void main(String[] args) {

        new Foo(); //prints: Empty constructor invoked

        new Foo(5);//prints: Empty constructor invoked
                   //prints: i initialized to : 5

        new Foo(null);//prints: Empty constructor invoked
                   //prints: i NOT initialized 
    }
}

关于java - 如何从另一个调用一个空的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44745859/

相关文章:

java - 获取字符串接受 string[] 作为参数?

java - 如何从 SQL 日期时间 UTC 转换为 LocalDateTime 并再次转换回来

java - 如何在 Java 中使用 jmockit 模拟静态链式方法

scala - 为什么辅助构造函数看不到类中的导入?

java - ArrayList 和 Array 作为构造函数的参数

c++ - 无法访问 C++ 中全局变量的构造函数中的静态(非原始)成员

javascript - new F 和 new F() 有什么不同吗?

python - 在Python 3中,父类(super class)可以多态调用子类的构造函数吗

java - 我知道如何从字符串中删除元音,但如何从字符串中删除某些空格

java - HashMap.put() 正在覆盖不同键的现有项目