简体   繁体   中英

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. But can we use new for the same?

To be more clear on the question, is Line-2 is valid? If it is (as the compiler did not complaint), why the output is null not 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. The current instance still has the field name set to 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 .

What you're trying to do is accomplished by the code you commented out:

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

Line 2 is valid statement. 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.

new Test0("Hello"){};

Above line will create an anonymous instance of Test0 class and assigned the value of Hello to the name variable. 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. Therefore name is null

In the memory it is like

在此输入图像描述

Because you create a new instance of Test0 with name "hello" but never use it.

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. Especially, t.name will be null .

Use this("Hello") .

Name is the instance variable. Instance variables are object-specific.

With new Test0("Hello"); you are creating a new instance of Test0.

If you would like to have t.getName() return "Hello" [I mean field value independent of object], change the name field to static:

static String name;

You can display output by using new keyword through below code..Since u have used public Test0(){new Test("Hello){};" here {} braces are not important..so when test0() constructor is called...Inside this constructor test0(args); is being called bt in first constructor u didnot displayed output..where will be your "Hello" will get displayed..so just edit

`

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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