简体   繁体   中英

Call parameter constructor from default constructor without using this keyword

I know that we can call a constructor from another constructor of the same class using the this keyword. But is it somehow possible to call the parameter constructor from within the default constructor without using this ?

I've tried:

class Example
{
    int x;

    public Example()
    {
         Example obj = new Example(2); 
    }

    public Example(int x)
    {
        this.x = x;
    }

}

But this doesn't let me assign value to x through the parameter constructor unless I use a getter method to get value from obj object. Is there a way to assign value to x by calling the parameter constructor only without using this? If not then why?

Why can't we do this?

Example(2); 

No, you can't.

Quoting JLS section 8.8.7 :

It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this .

You have to write:

public Example()
{
     this(2); // or this.x = 2
}

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