Illegal Conversions & UNSAFE Conversions between Related Classes:

  1. You CANNOT convert between UNRELATED objects:

    
        Rectangle r  = new Rectangle(10, 10, 50, 50);
        SavingsAccount harrysSaving = new SavingsAccount(1000, 5);
    
        r = harrysSaving;  // Disallowed
    
    

  2. Converting object reference from child type to parent type is SAFE (and it is allowed)

  3. Occasionally, after converting object reference from child type to parent type, you want to convert it back to a child type...

    Java allows conversion from parent type to child type using a casting operation:

    Example: casting
          SavingsAccount momsSaving = new SavingsAccount(10000, 5);
          SavingsAccount test;
          BankAccount temp;
    
          temp = momsSaving;             // Automatically allowed 
    
          test = (SavingsAccount) temp;  // Need casting
    
    

  4. WARNING:

  5. Different EFFECTS of type casting:

  6. NOTE:

  7. How to make avoid inadvertent illegal casting from child type to parent type:

    Use the instanceof operator:
    
          SavingsAccount momsSaving = new SavingsAccount(10000, 5);
          BankAccount    momsChecking = new BankAccount(1000);
    
          SavingsAccount testSaving;
          BankAccount    testChecking;
    
          testChecking = ...; (it has the ability to refer to 
    			   a SavingsAccount or a BankAccount object)  
    
          // We want set: testSaving = testChecking
          // But this is only allowed when testChecking
          // is pointing to a SavingsAccount object !
    
          if ( testChecking instanceof SavingsAccount )
          { 
             testChecking = (SavingsAccount) testChecking;
          }