Inherit parent constructor in child class

Parent class

class Noodle {
  
  String shape;
  
  Noodle(String shp) {
    this.shape = shp;
  }
  
  public static void main(String[] args) {
    Pho phoChay = new Pho();
    System.out.println(phoChay.shape);
  }
  
}

child class

class Pho extends Noodle {
  
 
  public Pho() {
    this.shape = "flat";
  }
  
}

Gives error : error: constructor Noodle in class Noodle cannot be applied to given types;

I cannot understand the issue here.

The Pho class has no explicit shape field, so you cannot use it in the constructor. But you can call Noodle’s constructor from the Pho class with the “super” keyword.

public Pho() {
    super("flat");
  }

Now a Pho object can have a shape field defined through its constructor.

1 Like