Constructors & Inheritance:

·

1 min read

Table of contents

By default,

the parent class's default constructor—which doesn't take any parameters—is invoked anytime the constructor of a subclass is called.

EG:

class parent{
    parent(){
        System.out.println("parent");
    }
}
public class inheri extends parent{
    int u;    
    inher(){
        System.out.println("inheri"); //parent() is first called.    
    }
    public static void main(String[] args) {
        inher r=new inher();    
    }
}
OUTPUT:
       parent
       child

Therefore, if the parent class doesn't have a default constructor, we will receive an Error (we will see how to avoid it).

WAYS TO AVOID IT:

  1. Add a default constructor in the parent class
class parent{
    int a;    
    parent(){
        a=10;    
    }
    parent(int a){
        this.a=a;    
    }
}
public class child extends parent{
    String name;    
    child(String n){
        this.name=n;    
    }
    public static void main(String[] args) {
        child r=new child("HI!");        
        System.out.println(r.name);    
    }
}

2.Use the super() keyword to call the parent class non-default constructor with the required parameters.

class parent{
    int a;    
    parent(int a){
        this.a=a;    
    }
}
public class child extends parent{
    String name;    
    child(String n){
        super(2); //dummy value        this.name=n;    
    }
    public static void main(String[] args) {
        child r=new child("HI!");        
        System.out.println(r.name);    
    }
}

If you don't require a specific value and are only trying to prevent an error, you can alternatively supply a dummy value, when calling the parent class constructor.