user94 user94 - 3 months ago 9
Java Question

Why is it necessary for parent class to have a default constructor if we do not create child class object in child class?

class handleException extends Exception
{
public handleException(String s)
{
super(s);
}
}

public class unhandled extends handleException {
public static void main(String args[])throws handleException
{
float a=7/0;
if(Double.isNaN(a))
{
throw new handleException("Exception is handled");
}
}


}


This code gives compile error saying that handleException which is the parent class does not have any default constructor ,but why is it so when child class constructor unhandled() is not called, so super() will not be called so why is it giving compile time error .

Answer

Basically currently you're dealing with only one type of constructor, i.e., Parameterized Constructor but actually there are two types of constructors.

  1. Default Constructor
  2. Parameterized Constructor

Types of constructors in java

The main point to note here is:

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Now you don't have any constructor defined your your class unhandled. So compiler will automatically create a constructor like this:

public class unhandled extends handleException {

    //added by compiler
    public unhandled() { 
        super(); //note that this super will call the non-parameterized constructor of your parent class, i.e., handleException
    }

    public static void main(String args[])throws handleException
    {
        float a=7/0;
        if(Double.isNaN(a))
        {
            throw new handleException("Exception is handled");
        }
    }
}

now the word super() doesn't have any arguments and so it's invoking the default OR non parameterized constructor of your parent class, and since your parent class handleException don't have that, so the compiler says:

Sorry, but `handleException` don't have a default constructor, I can't invoke that.
Comments