1

I was learning about constructor chaining and I got two cases. One is to initialize the parent classes which is okay. Java by default calls the constructor of the parent class and we can use super if we want.

The other case which I got was related to code redundancy. Below is an example.

class Student {
    int id;
    String name, city;

    Student ( int id, String name, String city ) {
        this(id, name);
        this.city = city;
    }

    Student(int id, String name) {
        this.id = id;
        this.name  = name;
    }
    
    void display() {
        System.out.println( this.id + this.city + this.name);
    }

}

// The above example is nice and I can see that I didn't have to write the code for initializing name and city but the same code can be written as below

class Student1 {
    int id;
    String name, city;

    Student1 ( int id, String name, String city ) {
        this.setStudent(id, name);
        this.city = city;
    }
    
    private void setStudent ( int id, String name) {
        this.id = id;
        this.name = name;
    }
    
    void display() {
        System.out.println( this.id + this.city + this.name);
    }
}

I am trying to understand if there is any specific use case where we would need constructor chaining and initializing with method style won't be applicable. If not then what is the advantage of one over the other or why the constructor chaining is preferred?

Asim
  • 413
  • 1
  • 4
  • 13
  • 5
    make the `id` and `name` members `final`, that way they **must** be initialized in the constructor and thus you can't use a method – Lino Sep 03 '20 at 09:57
  • 4
    It's not always needed, but it can be useful. Also your second approach won't work with final fields. – stonar96 Sep 03 '20 at 09:57
  • Related: https://stackoverflow.com/questions/17171012/how-to-avoid-constructor-code-redundancy-in-java – Lino Sep 03 '20 at 10:00
  • 2
    it's useful if you want to provide both constructor options. – Stultuske Sep 03 '20 at 10:03
  • 1
    Depends on the ways you want to instantiate an object. You can give multiple options by having different constructors, say you need certain combinations of fields to be mandatory. – Vladimir Stanciu Sep 03 '20 at 13:03
  • thanks, Lino and stonar96. That makes sense. Vladimir and Stultuske: I agree with both of you but I was thinking that the basic functionality could always be achieved via methods. But yes you guys are right providing constructor options would times be better than using setter and getter methods in many scenarios and also the methods wouldn't work with final fields. – Asim Sep 07 '20 at 08:29

0 Answers0