Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
    }
}
like image 258
Dexter Avatar asked Jun 06 '15 07:06

Dexter


People also ask

Can we call constructor inside another constructor?

Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.

Can a constructor be called inside another constructor in java?

Example 1: Java program to call one constructor from anotherInside the first constructor, we have used this keyword to call the second constructor. this(5, 2); Here, the second constructor is called from the first constructor by passing arguments 5 and 2.

Can we call a constructor inside a class in java?

No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.

Can we call another method from constructor in java?

Calling a method using this keyword from a constructorYes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.


2 Answers

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.

like image 185
M A Avatar answered Oct 13 '22 01:10

M A


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

public Test0()
{
    this("Hello");
}
like image 34
user207421 Avatar answered Oct 13 '22 00:10

user207421