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 - 计算字符串中逗号的数量,双引号之间的逗号除外

java - 我为 Rubymine 创建的插件不兼容

java - 忽略除字母和数字之外的任何内容的分隔符模式

c++ - 类模板构造函数中的 SFINAE

java - (主观)无效的 Java 类构造函数

java - org.apache.catalina.LifecycleException : Failed to start component [StandardEngine[Catalina]. StandardHost[localhost]]

java - 字符串文字作为方法的参数

c++ - try 和 catch 中的对象声明未在范围内定义

Java 驱动程序类对象声明错误

java - 为什么 this() 和 super() 不能在构造函数中一起使用?