Search code examples
javaobjectoopconstructor

Implicit super constructor Num() is undefined for default constructor. Must define an explicit constructor, what is the logic behind this


class Num 
{
    Num(double x) 
    { 
        System.out.println( x ) ; 
    }
}
class Number extends Num 
{ 
    public static void main(String[] args)
    { 
        Num num = new Num(2) ; 
    } 
} 

In the above program, its show the error. Please help me out.


Solution

  • When you define your own constructor,the compiler does not provide a no-argument constructor for you. When you define a class with no constructor,the compiler inserts a no-arg constructor for you with a call to super().

    class Example{
    }
    

    becomes

    class Example{
    
    Example(){
    super();   // an accessible no-arg constructor must be present for the class to compile.
    }
    

    However,it is not the case with your class as Number class cannot find a no-arg constructor for Num class.You need to explicity define a constructor for you with a call to any of the super constructor

    Solution:-

    class Num 
    {
        Num(double x) 
        { 
            System.out.println( x ) ; 
        }
    }
    
    class Number extends Num 
    { 
    
    
     Number(double x){
     super(x);
     }
    
     public static void main(String[] args)
        { 
            Num num = new Num(2) ; 
        } 
    }