mike_hornbeck
mike_hornbeck

Reputation: 1622

Constructor with fewer arguments from a constructor

I have Constructor Tree(int a, int b, int c) and second Constructor Tree(int a, int b, int c, String s). How to load second constructor from first just to save writing all the logics? I thought about something like this but it gives me 'null' object.

public Tree(int a, int b, int c){
    Tree t1 = new Tree(a, b, c, "randomString");
}

Upvotes: 4

Views: 724

Answers (4)

Justin Ardini
Justin Ardini

Reputation: 9866

You can simply call the other constructor directly, using the keyword this to refer to the class containing the method. So, what you want is:

public Tree(int a, int b, int c){
    this(a, b, c, "randomString");
}

Upvotes: 1

Joel
Joel

Reputation: 16655

in the first line of a constructor, you can call another constructor:

public Tree(int a, int b, int c, String s)
{
}

public Tree(int a, int b, int c)
{
    this(a,b,c,"someString");
}

Upvotes: 1

TofuBeer
TofuBeer

Reputation: 61516

public Tree(int a, int b, int c){
    this(a, b, c, "randomString");
}

Upvotes: 1

Rob
Rob

Reputation: 48369

The magic word is this, e.g.

public Tree( int a, int b, int c, String d ) {
    // Do something
}

public Tree( int a, int b, int c ) {
    this( a, b, c, "randomString" );
}

Upvotes: 10

Related Questions