Abstract Classes

  1. Abstract classes have the property of (ordinary) classes and interfaces:

  2. Example abstract class:

    Example of an Abstract Class:
       public abstract class BankAccount
       {
          private double balance;
    
          .... (other methods omitted)
    
          public abstract void deductFees();
    	// Watch out for the SEMI-COLON
    	// Abstract class contains methods WITHOUT body (code section)
       }
       
    

  3. Why do we need abstract methods ?

  4. Example:

  5. Design Attempt using ordinary class

    Designing BankAccount as an ordinary class:
       public class BankAccount
       {
          private double balance;
    
          public void deposit(...)  ....
          public void withdraw(...)  ....
          public double getBalance(...)  ....
    
          public void deductFees()
          {
             // What should this method do ???    
          }
       }
    
    

  6. Design using ABSTRACT class

    Designing BankAccount as an ABSTRACT class:
       public abstract class BankAccount
       {
          private double balance;
    
          public void deposit(...)  ....
          public void withdraw(...)  ....
          public double getBalance(...)  ....
    
          public abstract void deductFees(); 
       }
    
    

  7. An ordinary class that extends an abstract class must (re)define all the abstract methods

    Example:
        public class CheckingAccount extends BankAccount
        {
           ....
    
           // Must override abstract method dedectFees()
           public void deductFees()
           {
    	  ... (write code to deduct fee according to
    	  ...  the fee schedule for CheckingAccount)
           }
        }
        
    

    (The will be a compile error if one or more abstract method remains undefined in an ordinary class.)