Inheritance Review Solutions

    1. HappyFace hf = (HappyFace)f; Can't cast to HappyFace since it is actually a Bunny
    2. f.wink(10); the Face class does not have a wink method - need a cast
    3. valid
    4. Bunny b = new Face(this); a Bunny variable cannot reference a Face object
    5. no Bunny object created yet - can't call any methods
    6. valid
  1. The one inherited from HappyFace that overrides the one from Face
  2.  
    import java.applet.*;
    
    public class HairyHappyFace extends HappyFace
    {
       int hairLength;
       
       public HairyHappyFace(Applet a)
       {
          super(a);
          hairLength = 0;
       }
       
       public void cutHair(int amountToCut)
       {
          hairLength -= amountToCut;
          if (hairLength < 0)
             hairLength = 0;
       }
       
       public void wink(int howMany)
       {
          if (hairLength <= 10)
             super.wink(howMany);
       }
       
       public void draw()
       {
          super.draw();
          // draw the hair
       }
       
       public void erase()
       {
          super.erase();
          // erase the hair
       }
    } 
    1. It would cause an error. When referring to a Child object through a Parent reference you can only use methods from the Parent class. That's why in the following lines we cast it back to a Child. Then we can use methods only the Child knows about.
    2.  
      This is from class parent
      In the class Child
      In the class Child
      This is not in parent
      Child@15db9742
      x = 20
    3. In the Parent class there are two versions of the someMethod method. One of them has no parameters and the other has one int parameter.
    4. In the Child class the method someMethod() overrides the one from the Parent class with the same name. If a Child calls someMethod() it will use the one from the Child class, not the one that would have been inherited from the Parent class. It you called the version with one paremeter, then it would use the overloaded inherited one.