简体   繁体   English

可以在类的构造函数中使用“new”来调用Java中的另一个构造函数吗?

[英]Can “new” be used inside the constructor of the class to call another constructor in Java?

I know that this(...) is used to call one constructor of a class from another constructor. 我知道this(...)用于从另一个构造函数调用一个类的构造函数。 But can we use new for the same? 但是我们可以使用new的吗?

To be more clear on the question, is Line-2 is valid? 为了更清楚这个问题,Line-2是否有效? If it is (as the compiler did not complaint), why the output is null not Hello ? 如果是(因为编译器没有投诉),为什么输出为null而不是Hello

class Test0 {
    String name;

    public Test0(String str) {
        this.name= str;
    }

    public Test0() {
        //this("Hello");    // Line-1
        new Test0("Hello"){}; // Line-2
    }

    String getName(){
        return name;
    }
}

public class Test{
    public static void main(String ags[]){
        Test0 t = new Test0();
        System.out.println(t.getName());
    }
}

It is valid but it's creating a completely separate instance of Test0 (more specifically an instance of an anonymous subclass of Test0 ) inside that constructor, and it's not being used anywhere. 它是有效的,但它在该构造函数中创建一个完全独立Test0实例(更具体地说是Test0的匿名子类的实例),并且它没有在任何地方使用。 The current instance still has the field name set to null . 当前实例仍将字段name设置为null

public Test0() {
    // this creates a different instance in addition to the current instance
    new Test0("Hello"){};
}

Note that if you call the new operator with the no-argument constructor, you would get a StackOverflowError . 请注意,如果使用无参数构造函数调用new运算符,则会出现StackOverflowError

What you're trying to do is accomplished by the code you commented out: 您尝试做的是通过您注释掉的代码完成的:

public Test0()
{
    this("Hello");
}

Line 2 is valid statement. 第2行是有效的声明。 That is why compiler didn't show up any errors. 这就是编译器没有显示任何错误的原因。 But there you are creating an anonymous object. 但是你在那里创建一个匿名对象。 It will vanish soon after you exit from the constructor. 退出构造函数后,它很快就会消失。 Therefore the value is still null becuase nothing was assigned to that. 因此,该值仍然为null,因为没有分配给它。

new Test0("Hello"){};

Above line will create an anonymous instance of Test0 class and assigned the value of Hello to the name variable. 上面的行将创建一个Test0类的匿名实例,并将name值赋给name变量。 But since you are not referring the created anonymous instance, it will get disappear from the immediate after line. 但是,由于您没有引用创建的匿名实例,它将从后续行中消失。 So still you haven't assigned a value to the name variable of the instance that calls the particular code segment. 所以你还没有为调用特定代码段的实例的name变量赋值。 Therefore name is null 因此name为null

In the memory it is like 就像在记忆中一样

在此输入图像描述

Because you create a new instance of Test0 with name "hello" but never use it. 因为您创建一个名为“hello”的Test0的新实例,但从不使用它。

public Test() {

    new Test0("hello") // nothing is referencing this new object
}

You simply creating an object inside another constructor but it will have no effect on the instance being created by the first constructor call. 您只需在另一个构造函数中创建一个对象,但它对第一个构造函数调用创建的实例没有任何影响。

You can do this but the result of this new usage will be gone at the end of the constructor. 可以这样做,但这个new用法的结果将在构造函数的末尾消失。 Especially, t.name will be null . 特别是, t.name将为null

Use this("Hello") . 使用this("Hello")

Name is the instance variable. Name是实例变量。 Instance variables are object-specific. 实例变量是特定于对象的。

With new Test0("Hello"); 新的Test0(“你好”); you are creating a new instance of Test0. 您正在创建Test0的新实例。

If you would like to have t.getName() return "Hello" [I mean field value independent of object], change the name field to static: 如果您希望t.getName()返回“Hello”[我的意思是独立于对象的字段值],请将name字段更改为static:

static String name;

You can display output by using new keyword through below code..Since u have used public Test0(){new Test("Hello){};" 您可以通过以下代码使用new关键字来显示输出。因为您使用了public Test0(){new Test("Hello){};" here {} braces are not important..so when test0() constructor is called...Inside this constructor test0(args); 这里{}大括号并不重要。所以当test0()构造函数时......在这个构造函数里面test0(args); is being called bt in first constructor u didnot displayed output..where will be your "Hello" will get displayed..so just edit 在第一个构造函数中被调用bt你没有显示输出..将会显示你的“Hello”将显示..所以只需编辑

` `

public test0(String str)
{
 this.name=str;
System.out.println(str);
}`

And you will have ur desired output..See my below code.. 你会得到你想要的输出..见下面的代码..

class test01{
public test01(String str)
{System.out.println(str);
   }
public test01(){

    new test01("Print");
}
}public class Const {
public static void main(String args[])
{test01 t = new test01();

    //System.out.println(t.getName());
    }}

The output of this code will give u required String 此代码的输出将为您提供所需的String

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

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