Overriding Methods

  1. There are 3 ways to define METHODS in a child class:

  2. What is overriding a method:

    Example: Overriding
          public class BankAccount
          {
             private double balance;
    
    	 public void deposit(double amount)
    	 {
    	    balance = balance + amount;
             }
    	 ....
    	 .... (other methods omitted to save space)
          }
    
          public class CheckingAccount extends BankAccount   
          {
    	 int transactionCount;
    
    	 public void deposit(double x)
             {
    	    transactionCount = transactionCount + 1;
                // balance = balance + amount;
             } 
    	 ....
          }
    

  3. Effect of overriding a method:

    Example:
    
    

  4. Example each case:

    1. Override method called from outside child or parent class:
      • obviously you will use the method Method defined inside Child

    2. Override method called from inside child class:
      • obviously you will use the method Method defined inside Child

    3. Override method called from inside parent class:
      • That's a big question...
      • Originally (in Parent), Another() invokes Method() in Parent class.
      • Now in Child, the inherited method Another() sees 2 different "Method()" methods.
      • Which one would it pick ???

  5. Polymorphism:

    Methods defined in the PARENT class (which will be inherited by the child that invoke a overridden method deposit(), will NOW ALSO invoke the deposit() method defined inside the child class (CheckingAccount) !!!

    Example:

    
    

  6. The overridden method deposit() inside the PARENT class is still available for use (accessible) from inside THE CHILD class as:

    
         super.deposit(...)   
    
    

    This ability is especially useful (and necessary) when there are private variables defined in the parent class