繁体   English   中英

从参数化构造函数调用默认构造函数的任何方法?

[英]Any way to call the default constructor from a parameterized constructor?

假设我有以下代码

class C {
    int i;
    String s;

    C(){
        System.out.println("In main constructor");
        // Other processing
    }

    C(int i){
        this(i,"Blank");
        System.out.println("In parameterized constructor 1");
    }

    C(int i, String s){
        System.out.println("In parameterized constructor 2");
        this.i = i;
        this.s = s;
        // Other processing 
        // Should this be a copy-paste from the main contructor? 
        // or is there any way to call it? 
    }
    public void show(){
        System.out.println("Show Method : " + i + ", "+ s);
    }
}

我想知道,有什么办法,我可以从参数化的构造函数(在这种情况下为C(int i, String s)调用main(default)构造函数?

或者我只是将整个内容从main(默认)构造函数复制粘贴到参数化的结构,如上面代码中的注释所示?

注意

在参数化构造函数中设置了变量is之后,我需要调用默认构造函数,因为处理涉及这些变量。

编辑

我看到这篇文章 ,说将this()作为第一行将调用默认构造函数。 但是我需要在设置值后调用它。

调用this()会起作用,但是请注意,它必须是构造函数中的第一条语句。 例如:下面的代码将是非法的,将无法编译:

class Test {
    void Test() { }
    void Test(int i) {
        i = 9;
        this();
    }
}

一种选择是从默认构造函数调用参数化构造函数。

C(){
    this(0, "Blank");
}

C(int i){
    this(i,"Blank");
}

C(int i, String s){
    this.i = i;
    this.s = s;
}

通过该模式,您可以为构造函数提供默认值,而为更具体的构造函数提供较少的参数。

另外,注释链构造器必须作为另一个构造器中的第一个调用完成-初始化变量后不能调用另一个构造器:

C(int i, String s){
    this.i = i;
    this.s = s;
    this();     // invalid!
}

如果您确实想做这样的事情,请考虑使用init方法:

C() {
    init();
}
C(int i, String s) {
    this.i = i;
    this.s = s;
    init();
}

调用this()作为其他构造函数中的第一条语句就足够了。

C(int i, String s)
{
   this();
   // other stuff.
}

引用文档:

另一个构造函数的调用必须是该构造函数的第一行

所以没有不可能。 在第一行中使用this()。

您可以将所有代码从主构造函数移至某个方法,例如mainProcessing()。

C()
{
    System.out.println("In main constructor");
    mainProcessing();
}

private void mainProcessing()
{
    // Move your code from main constructor to here.
}

现在,在参数化的构造函数2中,可以在所需位置调用此方法mainProcessing()。

C(int i, String s)
{
    System.out.println("In parameterized constructor 2");
    this.i = i;
    this.s = s;
    mainProcessing();
}

只需调用构造函数ny this();即可。 声明作为默认构造函数的第一行。

您可以使用this(); 调用默认构造函数

C(int i, String s){
   this(); // call to default constructor
   // .....       
}

参数化构造函数的第一行中使用this()

C(int i, String s){
    this();
    System.out.println("In parameterized constructor 2");
    this.i = i;
    this.s = s;
    // Other processing
    // Should this be a copy-paste from the main contructor?
    // or is there any way to call it?
}

您可以在第一条语句中调用this()以在任何参数化的构造函数中调用默认构造函数。

请注意, this()必须强制为构造函数定义的第一行

C(int i, String s){
   this();
    . . . . 
}

但是我需要在设置值后调用它。

这不可能。 构造函数调用必须是第一个语句。

您可以通过以下链接: 构造函数调用必须是第一行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM