Constructor Methods in Inheritance

  1. Default constructor:

    Example: Default constructor
       public class BankAccount
       {  double balance;
    
          public BankAccount()  // Default constructor    
          {
             balance = 0;
          }
    
          public BankAccount(double init_amount) // NOT default constructor
          {
             balance = init_amount;
          }
          ....
       }
    
    

  2. Constructor methods in the parent class are NOT inherited by the child class

    Example: CheckingAccount
          public class CheckingAccount extends BankAccount  
          {
    	 // The constructors BankAccount() and 
    	 // BankAccount(double init_amount)
    	 // are NOT inherited
             ...
          }
    
    

  3. Defining constructor method in child class:

    Example: CheckingAccount
       public class CheckingAccount extends BankAccount
       {
          private static final int FREE_TRANSACTIONS = 3;
          private static final double TRANSACTION_FEE = 2.0;
          private int transactionCount;
    
          public CheckingAccount(double init_amount)
          {
             balance = init_amount;  // ??? Not allowed !!! 
    				 // balance is private variable !!! 
            
    	 transactionCount = 0;
          }
          ....
          .... (other methods omitted for brevity)
       }
       
    

    Child class needs a way to invoke constructor methods in parent class directly:

  4. Invoking constructor method in super class:

    Example: CheckingAccount
       public class CheckingAccount extends BankAccount
       {
          private static final int FREE_TRANSACTIONS = 3;
          private static final double TRANSACTION_FEE = 2.0;
          private int transactionCount;
    
          public CheckingAccount(double starting_amount)
          {
             super(starting_amount); // Will invoke **matching** constructor
    			         // in super class 
    				 // (BankAccount(double))... 
    				 // Note: must be the first statement
            
    	 transactionCount = 0;
          }
          ....
          .... (other methods omitted for brevity)
       }
       
    

    The CheckingAccount class example from text book:

  5. Some more Java language rules:

    The inheritance example from Horstmann text book: