Abhijeet Ahuja
Abhijeet Ahuja

Reputation: 5950

multiple constructors for final fields in java

I have some final fields in the class like

class A {

 private final boolean a;
 private final boolean b;

 public A(boolean a){
     this.a = a;
 }

 public A(boolean a, boolean b){
     this.a = a;
     this.b = b;
 }
}

But this gives an error that final field 'b' might not have been initialized. So any help would be appreciated on how to handle final attributes initialization in case of multiple constructors. It works fine if I have only the second constructor.

Upvotes: 4

Views: 3955

Answers (3)

Jerin Joseph
Jerin Joseph

Reputation: 1097

You can initialize b to default false. All the final variable should be initialized in constructors.

 public A(boolean a){
     this.a = a;
     this.b = false;
 }

Or should call other constructors which would initialize them.

 public A(boolean a){
     this(a, false);
 }

 public A(boolean a, boolean b){
     this.a = a;
     this.b = b;
 }

Upvotes: 7

you can call the constructor from another constructor too:

public class A{
    private final boolean a;
    private final boolean b;

    public A(boolean a){
        this(a,false);
    }

    public A(boolean a, boolean b){
        this.a = a;
        this.b = b;
    }
}

Upvotes: 2

Iłya Bursov
Iłya Bursov

Reputation: 24146

the problem is that first constructor does not initialize b, so java cannot assume any value, standard practice is to write code like this:

 public A(boolean a){
     this(a, DEFAULT VALUE FOR B);
 }

 public A(boolean a, boolean b){
     this.a = a;
     this.b = b;
 }

this way you have only 1 real constructor, all other constructors are just short-cuts for it

Upvotes: 6

Related Questions