3
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.

Eran
  • 387,369
  • 54
  • 702
  • 768
Tilak Raj
  • 472
  • 4
  • 12

3 Answers3

6

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) ; 
    } 
} 
Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35
0

Your constructor is defined for class double, yet you call Num with an integer argument. Integers aren't automatically promoted to doubles, and you have no default constructor, therefore you get a compilation error.

Ashalynd
  • 12,363
  • 2
  • 34
  • 37
0

as Asalynd provide the asnswer of this question correctly. Your constructor is defined for class double, yet you call Num with an integer argument. Integers aren't automatically promoted to doubles, and you have no default constructor, therefore you get a compilation error. you have to type cast before passing the argument in constructor