//Chapter 9 //part 5 constructors public class Inheritance5 { public static void main( String[] args ) { System.out.print( "creating an X: " ); X x1 = new X(); System.out.println( "" ); System.out.print( "creating an X(4): " ); X x2 = new X(4); System.out.println( "" ); System.out.print( "creating an Y(): " ); Y y1 = new Y(); System.out.println( "" ); System.out.print( "creating an Y(3.0): " ); Y y2 = new Y(3.0); System.out.println( "" ); System.out.print( "creating an Y(3): " ); Y y3 = new Y(3); } } class X { int superField; X() { System.out.println( "hello from X() constructor" ); } //if no constructor exists, compiler creates one (the "default // constructor" of no arguments) that does nothing. X( int sf ) { superField = sf; System.out.println( "hello from X(int) constructor" ); } //if any constructor exists, the default one will not be created. } class Y extends X { Y() { //implicit call to superclass no-arg constructor is here: super() System.out.println( "hello from Y() constructor" ); } Y( double d ) { //implicit call to superclass no-arg constructor is here. System.out.println( "hello from Y(double) constructor" ); } //if a subclass constructor implicitly (or explicitly) calls the no // argument constructor of superclass and it doesn't exist: syntax error Y( int i ) { //want to initialize inherited field, typically do so with //superclass's constructor. //don't want implicit call to superclass no-arg constructor. //need explicit call to superclass' X(int) constructor: super( i ); //the superclass must have such a constructor, else syntax error System.out.println( "hello from Y(int) constructor" ); } }