user3700788
user3700788

Reputation: 1

How to declare a constructor in a subclass when the superClass does not have a constructor

I am trying to implement a constructor for a subclass, however I keep getting "error: class, interface, or enum expected" when I compile.

My code for the overall looks like this:

public class Super{
    //methods go here, no constructor.
}

Here is what I tried but it did not work:

public class Sub extends Super{
    private boolean myCondition;
    public Sub(boolean condition){
        super();
        myCondition = condition;
    }
}

I would assume that I would not need to call super() in the subs constructor as the compiler should implicitly call it.

Thanks.

Upvotes: 0

Views: 68

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

Every class has a constructor. If you do not specify one, you get a default constructor. JLS-8.8.9 Default Constructor

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

It is a compile-time error if a default constructor is implicitly declared but the superclass does not have an accessible constructor (§6.6) that takes no arguments and has no throws clause.

In a class type, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.

So Super (a public class) has a default constructor inserted by the compiler that looks something like

public Super() {
  super();
}

Upvotes: 1

Related Questions