Intro to Inheritance

  1. Inheritance:

  2. When to use Inheritance:

  3. Example:

  4. Traditional way to RE-USE existing program:

  5. Object Oriented Programming Languages like Smalltalk, C++ and Java use the inheritance mechanism to re-use existing classes (programs):

    Example: make class SavingsAccount inherit from class BankAccount
          public class SavingsAccount extends BankAccount  
          {
             // ALL instance & class (static) variables 
             // in BankAccount class
             // are defined now in the SavingsAccount
             // class
             ....
             .... (all we have to do to complete
             .... the SavingsAccount class is to
             .... ADD variables & methods that are
             .... not defined in BankAccount class
    
    
             // Add new method....
             public void addInterest()
             {
    	    ....
    	    ....
             } 
          }
    

  6. All classes in Java inherits from the class Object in the Java library (java.lang.Object)

    In other words:

          public class BankAccount
          {
    	 ....
          }
    
    is actually:
    
          public class BankAccount extends Object    
          {
    	 ....
          }
    
    

  7. NOTE: inheritance is transitive

    Therefore: all variables & methods that are defined in the class Object are also defined in any class that you define in your Java program

  8. Methods defined in the class Object are "default" methods

    Because they work for ALL objects, they are necessarily general in nature

  9. Example default method: