如何在 Java 中从另一个构造函数调用一个构造函数?

新手上路,请多包涵

是否可以从另一个调用构造函数(在同一个类中,而不是从子类中)?如果是如何?调用另一个构造函数的最佳方法是什么(如果有多种方法)?

原文由 ashokgelal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 346
2 个回答

对的,这是可能的:

 public class Foo {
    private int x;

    public Foo() {
        this(1);
    }

    public Foo(int x) {
        this.x = x;
    }
}

要链接到特定的超类构造函数而不是同一类中的构造函数,请使用 super 而不是 this 。请注意, 您只能链接到一个构造函数,并且 它必须是构造函数主体中的第一条语句

另请参阅 此相关问题,该问题与 C# 有关,但适用相同的原则。

原文由 Jon Skeet 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 this(args) 。首选模式是从最小的构造函数到最大的构造函数。

 public class Cons {

    public Cons() {
        // A no arguments constructor that sends default values to the largest
        this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
    }

    public Cons(int arg1, int arg2) {
       // An example of a partial constructor that uses the passed in arguments
        // and sends a hidden default value to the largest
        this(arg1,arg2, madeUpArg3Value);
    }

    // Largest constructor that does the work
    public Cons(int arg1, int arg2, int arg3) {
        this.arg1 = arg1;
        this.arg2 = arg2;
        this.arg3 = arg3;
    }
}

您还可以使用最近提倡的 valueOf 方法或仅使用“of”:

 public class Cons {
    public static Cons newCons(int arg1,...) {
        // This function is commonly called valueOf, like Integer.valueOf(..)
        // More recently called "of", like EnumSet.of(..)
        Cons c = new Cons(...);
        c.setArg1(....);
        return c;
    }
}

要调用超类,请使用 super(someValue) 。对 super 的调用必须是构造函数中的第一个调用,否则会出现编译错误。

原文由 Josh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题