up previous next contents
Next: Overriding methods, hiding fields, Up: Extending Classes Previous: What protected really means   Contents

Subsections

Constructors in extended classes

  • When you extend a class, the new class must choose one of it's superclass's constructors to invoke.
  • If you do not invoke a superclass constructor as your constructors first executable statement, the superclass no-arg constructor is automatically invoked before any statements in your new constructor are executed.
  • If the superclass does not have a no-arg constructor, you must explicitly invoke one of the superclass's other constructors, or invoke another of your own constructors using the this construct.
  • If you use super(), it must be the first executable statement of the constructor.
  • The language provides a default no-arg constructor for you.

Constructor order dependencies

  • When an object is created, all it's fields are set to default initial values.
  • Then the constructor is invoked.

Constructor phases

  • Invoke a superclass's constructor.
  • Initialize the fields using their initializers and any initialization blocks.
  • Execute the body of the constructor.

Constructor phase example

  • An example of how parent/child constructors work:
    public class ParentClass {
      public ParentClass() {
        System.out.println( "ParentClass constructor was called" );
      }
    }
    public class ChildClass extends ParentClass {
      public ChildClass() {
        System.out.println( "ChildClass constructor was called" );
      }
    }
    public class Main {
      public static void main(String[] args) {
        ChildClass cc = new ChildClass();
      }
    }
    


up previous next contents
Next: Overriding methods, hiding fields, Up: Extending Classes Previous: What protected really means   Contents