Search code examples
javainheritanceconstructorabstract-classdefault-constructor

Why do I need another constructor in an extended abstract class?


I've come across this issue and I'm wondering what is the difference here:

abstract class Abstract {
    Abstract() {
        System.out.println("Abstract.Abstract()");
    }

    Abstract(String s) {
        System.out.println("Abstract.Abstract(String)");
    }

    void test() {
        System.out.println("Abstract.test()");
    }

    void test(String s) {
        System.out.println("Abstract.test(s)");
    }
}

abstract class Base extends Abstract {
}

class Sub extends Base {
    Sub(String s) {
        super(s);   // undefined constructor
    }

    void subTest(String s) {
        super.test(s);  // why is this all right then?
    }
}

Why do I have to define Base(String s) constructor to make it compilable but the super.test(s) call is fine without defining anything?


Solution

  • Java provides you with default constructors in any class (even if you don't define one yourself), meaning you have Base() default constructor in class Base, but not any other constructor (one that takes arguments, such as Base(String s)) because constructors are not inherited .

    In addition, extending a class gives you its methods via inheritance, so calling super.test(s) is legal here because Base has the method test(String s) inherited from Abstract.