view raw
Dexter Dexter - 6 months ago 25
Java Question

Can "new" be used inside the constructor of the class to call another constructor in Java?

I know that

is used to call one constructor of a class from another constructor. But can we use
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

class Test0 {
String name;

public Test0(String str) { 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();


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.