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 constructor, one must define all constructors.
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.
So, the following would work:
class B { int x; B() { } // a constructor B( int n ) { x = n; } // a constructor int returnMe() { return x; } } class C extends B { }
or this:
class B { int x; B( int n ) { x = n; } // a constructor int returnMe() { return x; } } class C extends B { C () { super(0); } // a constructor C (int n) { super(n); } // a constructor }
If you want to make sure 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.