Extending A Class That Has Default Constructers

Xah Lee, 2005-02

In the following code, why it doesn't compile, but does when B() is defined?


class B {
  int x;
  //B () {x=300;}
  B (int n) {x=n;}
  int returnMe () {return x;}
}

class C extends B {
}

public class inh3 {
  public static void main(String[] args) {
  }
}

(answer follows below.)


the answer to the constructor mystery is that, if one provides any constructer, one must define all constructers.

Peter Molettiere on Apple's Java forum has provided excellent answers:

Because there is no default constructor available in B, as the
compiler error message indicates. Once you define a constructor in a
class, the default constructor is not included. If you define *any*
constructor, then you must define *all* constructors.

When you try to instantiate C, it has to call super() in order to
initialize its super class. You don't have a super(), you only have a
super(int n), so C can not be defined with the default constructor C()
{ super(); }. Either define a no-arg constructor in B, or call
super(n) as the first statement in your constructors in C.

That is to say, this:
   class B {
       int x;
       B() { } // a constructor
       B( int n ) { x = n; } // a constructer
       int returnMe() { return x; }
   }

   class C extends B {
   }

or this:

   class B {
       int x;
       B( int n ) { x = n; } // a constructer
       int returnMe() { return x; }
   }

   class C extends B {
       C () { super(0); } // a constructer
       C (int n) { super(n); } // a constructer
   }

If you want to ensure that x is set in the constructor, then the second solution is preferable.


Also, see java lang spec http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#41652. Quote:

8.8.7 Default Constructor

If a class contains no constructor declarations, then a default
constructor that takes no parameters is automatically provided:

   * If the class being declared is the primordial class Object, then
   the default constructor has an empty body.

   * Otherwise, the default constructor takes no parameters and simply
   invokes the superclass constructor with no arguments.

A compile-time error occurs if a default constructor is provided by
the compiler but the superclass does not have an accessible
constructor that takes no arguments.

See also:

• constructers does not have a return type declaration. See constructer and return type.

super keyword (inheritence of class with constructers).


Page created: 2005-01.
© 2005 by Xah Lee.
Xah Signet