javainheritanceparameter-passing

why cant we have a parameterized constructor of parent class when no value is being passed in the child class?


class a{
    a(int age){}
}
class b extends a{}
public class HelloWorld {
    public static void main(String[] args) {
        b var1=new b();
        System.out.println("Try programiz.pro");
    }
}

above code doesnt work.if i include the statement super(10) in child class constructor, it works.

but without any constructor in a ,it works like below

class a{}
class b extends a{}
public class HelloWorld {
    public static void main(String[] args) {
        b var1=new b();
        System.out.println("Try programiz.pro");
    }
}

if that is because we are required to give default constructor of super class in 2nd code we havent specified the constructor and still it works.can you explain why?


Solution

  • In Java, the compiler inserts a default constructor if and only if no explicit constructor has been defined for the class1. This default constructor:

    That last bit is why your first code example fails to compile. Your A class has defined an explicit constructor which has one parameter, thus it does not have a zero-parameter constructor to invoke from the default constructor of subclass B.


    First case

    When you have:

    public class A {
    
      // Explicit constructor
      public A(int arg) {}
    }
    
    public class B extends A {}
    

    That is the same as writing:

    public class A extends Object {
    
      // Note: No default constructor.
    
      // Explicit constructor
      public A(int arg) {
          super(); // OKAY: The 'Object' class has a no-arg constructor.
      }
    }
    
    public class B extends A {
    
      // Default constructor
      public B() {
          super(); // ERROR: The 'A' class does not have a no-arg constructor.
      }
    }
    

    Second case

    When you have:

    public class A {}
    
    public class B extends A {}
    

    That is the same as writing:

    public class A extends Object {
    
      // Default constructor
      public A() {
        super(); // OKAY: The 'Object' class has a no-arg constructor.
      }
    }
    
    public class B extends A {
    
      // Default constructor
      public B() {
        super(); // OKAY: The 'A' class has a no-arg constructor.
      }
    }
    

    1. See §8.8.7. Constructor Body and §8.8.9. Default Constructor of the Java Language Specification.

    2. Note every constructor has an implicit call to super() unless there is an explicit call to a super constructor or an explicit delegation to another constructor in the same class (i.e., this(...)). See §8.8.7. Constructor Body of the Java Language Specification.